c# – AutoMapper – 如何映射到三级深度
发布时间:2020-12-15 22:20:40 所属栏目:百科 来源:网络整理
导读:我正在尝试使用AutoMapper来压缩与另一个实体相关的实体,该实体与第三个实体有关,以查看模型 如何将这三个实体合二为一? 资源: public class Address{ public int AddressId { get; set; } public string AddressLine1 { get; set; } public int CityId {
我正在尝试使用AutoMapper来压缩与另一个实体相关的实体,该实体与第三个实体有关,以查看模型
如何将这三个实体合二为一? 资源: public class Address { public int AddressId { get; set; } public string AddressLine1 { get; set; } public int CityId { get; set; } public virtual City City { get; set; } } public class City { public int CityId { get; set; } public string CityName { get; set; } public int CountryId { get; set; } public virtual Country Country { get; set; } public virtual ICollection<Address> Addresses { get; set; } } public class Country { public int CountryId { get; set; } public string CountryName { get; set; } public virtual ICollection<City> Cities { get; set; } } 目的地: Public Class AddressViewModel { public int AddressId { get; set; } public string AddressLine1 { get; set; } public int CityId { get; set; } public string CityName { get; set; } public int CountryId { get; set; } public string CountryName { get; set} } 解决方法
有两种方式(至少).如果以不同的方式命名viewmodel字段,则可以按惯例进行:
Public Class AddressViewModel { public int AddressId { get; set; } public string AddressLine1 { get; set; } public int CityCityId { get; set; } [DisplayName("City Name")] public string CityCityName { get; set; } public int CityCountryCountryId { get; set; } [DisplayName("Country Name")] public string CityCountryCountryName { get; set} } 如果那太难看了,你可以在CreateMap中做到: Mapper.CreateMap<Address,AddressViewModel>() .ForMember(dest => dest.CityId,opts => opts.MapFrom(src => src.City.CityId)) .ForMember(dest => dest.CityName,opts => opts.MapFrom(src => src.City.CityName)) .ForMember(dest => dest.CountryId,opts => opts.MapFrom(src => src.City.Country.CountryId)) .ForMember(dest => dest.CountryName,opts => opts.MapFrom(src => src.City.Country.CountryName)); http://automapper.codeplex.com/wikipage?title=Flattening&referringTitle=Home (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- 解决jenkins构建job报错“NoClassDefFoundError” in jenki
- send_keys报错element not interactable
- jstl中的fn标签
- 使用PowerShell更新RootFolder的Properties属性
- React学习笔记—表单
- 可以为Ruby方法参数和访问器方法使用相同的名称吗?
- vue.js vue-router如何实现无效路由(404)的友好提示
- oracle – 使用DBMS_METADATA.GET_DDL为没有模式名称的对象
- ruby-on-rails – 在Rails中调试?
- c – 为什么std :: min_element和公司不专门用于std :: vec