微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – AutoMapper – 如何映射到三级深度

我正在尝试使用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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐