许多对许多插入存储库实体框架

时间:2017-04-06 14:32:07

标签: 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; }
    [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();
        }
}

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

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

抱歉英语不好:(

1 个答案:

答案 0 :(得分:0)

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

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

之后,您可以保存存储ProductColorsColorId的新实体ProductId。您的实体ColorProduct可以引用此表,而不是ColorProduct表。

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