怪物奇妙物语

宇宙无敌超级美少男的怪物奇妙物语

首页 新随笔 联系 管理
  819 随笔 :: 0 文章 :: 2 评论 :: 16万 阅读

AutoMapper的默认映射规则 convertions map complex object to flat/simple ones

Default conventions

AutoMapper uses the following conventions:

  • It will automatically map properties with the same names.

  • If the source object has some association with other objects,
    then it will try to map with properties on the destination object
    whose name is a combination of the source class name and property name in the Pascal case.

如下所示:

UserViewModel userViewModel = _mapper.Map<UserViewModel>(user);
public class User
{
public Address Address { get; set; }
}
public class Address
{
public string Country { get; set; }
}
public class UserViewModel
{
[Display(Name = "Country")]
public string AddressCountry { get; set; }
}
  • It will try to map methods on the source object
    which has a Get prefix with a property
    on the destination object
    with the name excluding the Get prefix.

如下所示:

UserViewModel userViewModel = _mapper.Map<UserViewModel>(user);
public class User
{
public string GetFullName()
{
return $"{this.LastName}, {this.FirstName}";
}
}
public class UserViewModel
{
[Display(Name = "Full Name")]
public string FullName { get; set; }
}

If we follow these conventions, AutoMapper will automatically map our objects. Otherwise, we’ll need to configure AutoMapper using Fluent API.

例子

Let’s modify our User object by adding a child object Address:

public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public Address Address { get; set; }
public string GetFullName()
{
return $"{this.LastName}, {this.FirstName}";
}
}

And here’s how the Address class looks like:

public class Address
{
public int Id { get; set; }
public string Door { get; set; }
public string Street1 { get; set; }
public string Street2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
public string ZipCode { get; set; }
}

Also, note that we have added a method GetFullName() to get the user’s full name.

Let’s modify the UserViewModel class:

public class UserViewModel
{
[Display(Name = "Full Name")]
public string FullName { get; set; }
[Display(Name = "Country")]
public string AddressCountry { get; set; }
public string Email { get; set; }
}

Now, Let’s modify the profile class to use the default conventions:

public UserProfile()
{
CreateMap<User, UserViewModel>();
}
posted on   超级无敌美少男战士  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· Trae初体验
历史上的今天:
2022-12-26 ECharts 的 series 配置项主要有以下几种
点击右上角即可分享
微信分享提示