![](/img/trans.png)
[英]Fluent NHibernate: How do I map Many-to-Many Relationships with additional attributes on the relationship table?
[英]How do you map many-to-many relationships?
一个人如何映射多对多关系?
一对一的关系很容易...
假设...
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; }
由于Ids现在是集合,如何更改CreateMap? 自动完成功能不再显示ID,而我得到的只是函数。
我是C#的新手,所以我很多人都缺少明显的东西。 我是否应该在for循环中迭代并逐个映射ID?
您可以尝试使用:
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。 在大多数情况下,一次通话中向服务传递更多数据比进行几次通话更好(更有效)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.