entity-framework - Entity Framework 多对多实体?

标签 entity-framework

这不是另一个关于如何创建多对多关系的问题,而是如何实际控制映射该关系的实体?

例如...表“产品”和表“供应商”之间的多对多关系。

我需要一个SupplierProduct,其中包含特定于产品+供应商组合的列。

class SupplierProduct {
    public int SupplierId { get; set; }
    public int ProductId { get; set; }

    // additional properties specific to a S+P combo: 
    public bool IsProductAssembled { get; set; }
}

一些供应商进行组装,另一些则不进行组装。如果我有这样的类,如何使用它来代替它创建的默认 EF 多对多表?

最佳答案

使用您的 SupplierProduct 类作为关系:

class SupplierProduct {
    public int SupplierId { get; set; }
    public int ProductId { get; set; }

    // additional properties specific to a S+P combo: 
    public bool IsProductAssembled { get; set; }
}

class Product {
    // ... lot of properties

    // Link all the suppliers of this products
    public IList<SupplierProduct> Suppliers { get; set; }
}    

class Supplier {
    // ... lot of properties

    // Link all the product this supplier supplies
    public IList<SupplierProduct> Products { get; set; }
}

然后,将 Product 配置为拥有大量 Suppliers,并将 Supplier 配置为拥有大量 Products产品供应商之间不再有直接关系。

配置模型绑定(bind)器:

modelBuilder.Entity<Product>()
    .HasMany<SupplierProduct>(p => p.Suppliers)
    .WithRequired();

modelBuilder.Entity<Supplier>()
    .HasMany<SupplierProduct>(s => s.Products)
    .WithRequired();

关于entity-framework - Entity Framework 多对多实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19598598/

相关文章:

c# - 如何将用户/权限关系定义为 M :M?

entity-framework - 在 AutoMapper 8.0 中缺少 ResolveUsing

c# - 定期更改基础 EF 模型的最佳替代方案

entity-framework - 使用Linq To Entities中的多列联接表

c# - Entity framework如何获取两年之间的所有数据?

c# - 将 session 拥有的 SQL Server sp_getapplock 与 EF6 DbContexts 一起使用是否安全?

c# - EF 代码优先 : Add row to table with a non-identity primary key

C# Linq 字符串与 indexOf 比较

c# - 从 IDbCommandInterceptor 的实现中获取 DbContext

c# - EF6 : getting data from derived DbSet