实体框架多对多实体?

时间:2013-10-25 20:07:47

标签: entity-framework

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

例如......表Product和table Supplier之间的多对多关系。

我需要一个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多对多表?

1 个答案:

答案 0 :(得分:2)

使用您的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以使大量SuppliersSupplier拥有大量Products。 <{1}}和Product之间没有直接关系。

配置模型绑定器:

Supplier