自动映射多对多映射

帕特里克,感谢关于正确问题的建议!

编辑1:

我有三张桌子可供多对多关系。 像这样: EF数据模型

GoodEntity:

public partial class GoodEntity { public GoodEntity() { this.GoodsAndProviders = new HashSet(); } public int id { get; set; } public string name { get; set; } public string description { get; set; } public decimal cost { get; set; } public Nullable price { get; set; } public virtual ICollection GoodsAndProviders { get; set; } } 

ProviderEntity:

 public partial class ProviderEntity { public ProviderEntity() { this.GoodsAndProviders = new HashSet(); } public int id { get; set; } public string name { get; set; } public string description { get; set; } public string address { get; set; } public string phone { get; set; } public string email { get; set; } public string url { get; set; } public Nullable rating { get; set; } public virtual ICollection GoodsAndProviders { get; set; } } 

多对多关系的实体:

 public partial class GoodAndProviderEntity { public int id { get; set; } public int good_id { get; set; } public int provider_id { get; set; } public virtual GoodEntity Goods { get; set; } public virtual ProviderEntity Providers { get; set; } } 

GoodDTO:

 public class GoodDTO { public int id { get; set; } public string name { get; set; } public string description { get; set; } public decimal cost { get; set; } public decimal? price { get; set; } public IList providers { get; set; } } 

ProviderDTO:

 public class ProviderDTO { public int id { get; set; } public string name { get; set; } public string description { get; set; } public string address { get; set; } public string phone { get; set; } public string email { get; set; } public string url { get; set; } public int? rating { get; set; } } 

这是创建地图的代码:

 Mapper.CreateMap(); Mapper.CreateMap(); Mapper.CreateMap() .ForMember(dto => dto.providers, opt => opt.MapFrom(x => x.GoodsAndProviders)); Mapper.CreateMap(); 

它的工作量减半。 Automapper已完全映射到“商品”,并为此商品的所有提供商创建了列表。 但是,automapper不会填补提供者。 在此处输入图像描述

如果我使用Mapper.AssertConfigurationIsValid(),那么:

找到了未映射的成员。 查看下面的类型和成员。 添加自定义映射表达式,忽略,添加自定义解析程序或修改源/目标类型============================== ========================= ProviderDTO – > ProviderEntity(目标成员列表)Core.DTO.ProviderDTO – > DAL.EF.Entities.ProviderEntity(目的地)成员列表)未映射的属性:GoodsAndProviders =========================================== =================== GoodAndProviderEntity – > ProviderDTO(目标成员列表)DAL.EF.Entities.GoodAndProviderEntity – > Core.DTO.ProviderDTO(目标成员列表)

如何为多对多关系创建映射?

此致,安东

使用当前代码,您尝试将GoodAndProviderEntity映射到ProviderDTO。

 Mapper.CreateMap() .ForMember(dto => dto.providers, opt => opt.MapFrom(x => x.GoodsAndProviders)); 

你想要做的是将ProviderEntity映射到ProviderDTO,所以你要做的就是从GoodsAndProviders中选择Providers作为列表:

  Mapper.CreateMap() .ForMember(dto => dto.providers, opt => opt.MapFrom(x => x.GoodsAndProviders.Select(y => y.Providers).ToList()));