如何映射多对多关系?
一对一的关系很容易......
假设...
public class ProductDTO
{
public int Id { get; set; }
public string Name { get; set; }
public int SupplierId { get; set; }
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public double Cost { get; set; }
public Supplier Supplier { get; set; }
}
public class Supplier
{
public int Id { get; set; }
public string Name { get; set; }
public int Rating { get; set; }
public ICollection<Product> Products { get; set; }
}
Mapper.CreateMap<Product, ProductDTO>()
.ForMember(d => d.SupplierId, m => m.MapFrom(s => s.Supplier.Id));
假设每个产品只有一个供应商并且一个供应商可以有很多产品。如果一个产品也可以有很多供应商,我该如何映射它?
我将产品中的供应商行更改为
public ICollection<Supplier> Supplier { get; set; }
并在 ProductDTO 中做同样的事情
public ICollection<int> SupplierId { get; set; }
由于 Id 现在是集合,如何更改 CreateMap?自动完成不再显示 Id,我得到的只是函数。
我是 C# 的新手,所以我很多人都遗漏了一些明显的东西。我是否应该在 for 循环中迭代并一一映射 ID?