gpt4 book ai didi

c# - AutoMapper - 如何映射到三层深度

转载 作者:行者123 更新时间:2023-11-30 12:42:46 24 4
gpt4 key购买 nike

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

最佳答案

有几种方式(至少)。如果您以不同的方式命名您的 View 模型字段,它可能会按照约定发生:

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

关于c# - AutoMapper - 如何映射到三层深度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32724461/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com