2

如何映射多对多关系?

一对一的关系很容易......

假设...

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?

4

1 回答 1

1

您可以尝试使用:

Mapper.CreateMap<Product, ProductDTO>()         
      .ForMember(d => d.SupplierIds, m => m.MapFrom(p => p.Suppliers.Select(s => s.Id)));

另外一个选项:

Mapper.CreateMap<Supplier, int>().ConvertUsing(s => s.Id);
Mapper.CreateMap<Product, ProductDTO>()                                
   .ForMember(d => d.SupplierIds, m => m.MapFrom(p => p.Suppliers));

如果您使用 DTO 从 Web/WCF 服务传递数据,您可以考虑使用另一件事

public ICollection<SupplierDTO> Supplier { get; set; }

相反,如果仅传递供应商 ID。在大多数情况下,在一次调用中向服务传递更多数据比进行几次调用更好(也更有效)。

于 2012-12-12T13:09:15.933 回答