Asp.net mvc 使用存储库实体框架进行多对多插入

Asp.net mvc 使用存储库实体框架进行多对多插入,asp.net-mvc,model-view-controller,repository-pattern,Asp.net Mvc,Model View Controller,Repository Pattern,我的实体: public class Product : Base.BaseEntity { public Product() { this.Colors = new HashSet<Color>(); } [StringLength(50)] public string ProductName { get; set; } public int CategoryID { get; set; } [StringL

我的实体:

public class Product : Base.BaseEntity
{
    public Product()
    {
        this.Colors = new HashSet<Color>();
    }

    [StringLength(50)]
    public string ProductName { get; set; }
    public int CategoryID { get; set; }
    [StringLength(100)]
    public string StockFinishes { get; set; }
    [StringLength(50)]
    public string Guarantee { get; set; }
    [StringLength(50)]
    public string Installation { get; set; }

    public virtual ProductEntity.Category OwnerCategory { get; set; }
    public virtual IList<VariationEntity.Variation> Variations { get; set; }
    public virtual ICollection<ProductEntity.Color> Colors { get; set; }
}

public class Color : Base.BaseEntity
{
    public Color()
    {
        this.Products = new HashSet<Product>();
    }

    [StringLength(50)]
    public string ColorName { get; set; }

    public virtual ICollection<ProductEntity.Product> Products { get; set; }
}
没有错误,但产品颜色未插入数据库。我不能使用存储库

如何在有存储库或无存储库的情况下添加产品颜色


抱歉英语不好:(

我更喜欢自己管理多对多关系,而不是实体框架

在我看来,您需要另一个表来存储具有列
ColorId
ProductId
的产品颜色。然后在
DbContext
上应该有一个
DbSet

之后,您可以保存一个新实体
ProductColors
,该实体存储
ColorId
ProductId
。您的实体
Color
Product
可以引用此表,而不是
Color
Product

public class ProductColor : Base.BaseEntity
{
    public ProductColor()
    {
    }

    public int ColorId { get; set; }
    public virtual Color Color { get; set; }

    public int ProductId { get; set; }
    public virtual Product Product { get; set; }
}
public class ProductColor : Base.BaseEntity
{
    public ProductColor()
    {
    }

    public int ColorId { get; set; }
    public virtual Color Color { get; set; }

    public int ProductId { get; set; }
    public virtual Product Product { get; set; }
}