当我的实体之间存在一对多的关系时,我的应用程序工作正常,但现在我已经尝试将其切换为多对多,我正在努力如何正确插入它。我想我的模特中可能有一些不太正确的东西。
现在,当我在控制器中运行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.
我查看了查询。我有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,但我没有该表的模型。