多对多插入存储库 Entity Framework

Many to many insert with repository Entity Framework

我的实体:

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; }
}

我的控制器:

[HttpPost]
public ActionResult NewProduct(Models.DTO.ProductDTO.ProductVM productmodel)
{
        if (ModelState.IsValid)
        {
            DATA.Models.ORM.Entity.ProductEntity.Product productentity = new DATA.Models.ORM.Entity.ProductEntity.Product();

            productentity.ProductName = productmodel.ProductName;
            productentity.CreatedBy = User.UserId;
            productentity.CategoryID = productmodel.CategoryID;
            productentity.StockFinishes = productmodel.StockFinishes;
            productentity.Guarantee = productmodel.Guarantee;
            productentity.Installation = productmodel.Installation;

            rpproduct.Insert(productentity);
            rpproduct.SaveChanges();

            if (productmodel.SelectedColors != null)
            {
                foreach (var colorId in productmodel.SelectedColors)
                {
                    DATA.Models.ORM.Entity.ProductEntity.Color color = rpcolor.FirstOrDefault(x => x.Id == colorId);
                    productentity.Colors.Add(color);
                }

                db.SaveChanges();
            }

            return RedirectToAction("ProductList");
        }
        else
        {
            ViewBag.Error = "An error occurred while adding a new product";
            return View();
        }
}

没有错误,但产品颜色没有插入数据库。我不能用存储库来做。

如何使用存储库或不使用存储库添加产品颜色?

抱歉英语不好:(

我更喜欢自己管理多对多关系而不是 Entity Framework。

在我看来,您需要另一个 table 来存储具有列 ColorIdProductId 的产品颜色。那么你的DbContext上应该有一个DbSet

之后,您可以保存一个新实体 ProductColors,其中存储 ColorIdProductId。您的实体 ColorProduct 可以引用此 table,而不是 ColorProduct table.

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; }
}