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 aGet
prefix with a property
on the destination object
with the name excluding theGet
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>(); }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 推荐几款开源且免费的 .NET MAUI 组件库
· 实操Deepseek接入个人知识库
· 易语言 —— 开山篇
· Trae初体验
2022-12-26 ECharts 的 series 配置项主要有以下几种