插入与多对多关系的记录

当我的实体之间有一对多关系时,我的应用程序工作正常,但现在我试图将其切换为多对多关系,而且我正在努力解决如何正确插入它的问题。 我想我的模型可能有些不太合适。

现在,当我在我的控制器中运行context.saveChanges()时,由于此错误而Failed in 97 ms with error: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Products_dbo.Categories_CategoryID". The conflict occurred in database "database", table "dbo.Categories", column 'ID'. The statement has been terminated.Failed in 97 ms with error: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Products_dbo.Categories_CategoryID". The conflict occurred in database "database", table "dbo.Categories", column 'ID'. The statement has been terminated. Failed in 97 ms with error: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Products_dbo.Categories_CategoryID". The conflict occurred in database "database", table "dbo.Categories", column 'ID'. The statement has been terminated. 我看了看查询。 我有3个现有类别的ID为1,2和3.现在在我的查询CategoryID为0,但我的IEnumerable CategoryIDs有1和2,这是我想要的。 我该如何着手让它进入类别1和类别2的产品?

类别型号:

public class CategoryModel
{
    public int ID { get; set; }

    [Required(ErrorMessage = "Required")]
    [Display(Name = "Category Name")]
    [MaxLength(50)]
    public String categoryName { get; set; }

    [MaxLength(50)]
    public String categoryDBName { get; set; }

    [DefaultValue(true)]
    [Display(Name = "Active?")]
    public bool isActive { get; set; }

    public ICollection<ProductModel> ProductList { get; set; }

}

产品型号:

public class ProductModel
{
    public int ID { get; set; }

    [Required(ErrorMessage = "Required")]
    [Index("ItemNumber", 1, IsUnique = true)]
    [Display(Name = "Item #")]
    public int itemNumber { get; set; }

    [Required(ErrorMessage = "Required")]
    [Display(Name = "Product")]
    [MaxLength(50)]
    public String product { get; set; }

    [Display(Name = "Description")]
    [MaxLength(500)]
    public String description { get; set; }

    [DefaultValue(true)]
    [Display(Name = "Active?")]
    public bool active { get; set; }

    [Display(Name = "Image Name")]
    public String imageName { get; set; }

    [Display(Name = "PDF Name")]
    public String PDFName { get; set; }

    [ForeignKey("Category")]
    public int CategoryID { get; set; }

    public IEnumerable<int> CategoryIDs { get; set; }

    public virtual CategoryModel Category { get; set; }

    public IEnumerable<SelectListItem> CategorySelectList { get; set; }

    public ICollection<CategoryModel> CategoryList { get; set; }

    public virtual BrochureModel Brochure { get; set; }

    public IEnumerable<SelectListItem> BrochureList { get; set; }

    public static IEnumerable<SelectListItem> getCategories(int id = 0)
    {
        using (var db = new ProductContext())
        {
            List<SelectListItem> list = new List<SelectListItem>();
            var categories = db.Categories.ToList();
            foreach (var cat in categories)
            {
                SelectListItem sli = new SelectListItem { Value = cat.ID.ToString(), Text = cat.categoryName };

                if (id > 0 && cat.ID == id)
                {
                    sli.Selected = true;
                }
                list.Add(sli);
            }
            return list;
        }

    }

    public ProductModel()
    {
        active = true;
    }

}

这里是控制器中保存更改的方法:

// POST
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult EditProduct([Bind(Include = "ID,itemNumber,product,description,active,PDFName,imageName,CategoryIDs")] ProductModel model)
    {
        if (ModelState.IsValid)
        {
            using (var context = new ProductContext())
            {
                context.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
                if (model.ID == 0)
                {
                    // Since it didn't have a ProductID, we assume this
                    // is a new Product
                    if (model.description == null || model.description.Trim() == "")
                    {
                        model.description = "Our Famous " + model.product;
                    }
                    if (model.imageName == null || model.imageName.Trim() == "")
                    {
                        model.imageName = model.itemNumber + ".jpg";
                    }
                    if (model.PDFName == null || model.PDFName.Trim() == "")
                    {
                        model.PDFName = model.itemNumber + ".pdf";
                    }
                    Session["dropdownID"] = model.CategoryID;
                    context.Products.Add(model);
                }
                else
                {
                    // Since EF doesn't know about this product (it was instantiated by
                    // the ModelBinder and not EF itself, we need to tell EF that the
                    // object exists and that it is a modified copy of an existing row
                    context.Entry(model).State = EntityState.Modified;
                }
                context.SaveChanges();
                return RedirectToAction("ControlPanel");
            }
        }
        return View(model);
    }

编辑:我忘了提及我有第三个名为ProductCategory的表,它有一个ProductID和一个CategoryID,但我没有该表的模型。

链接地址: http://www.djcxy.com/p/33489.html

上一篇: inserting record with many to many relationship

下一篇: Updating a belongs to with Entity Framework