我有两个应该是相关的表。MVC:INSERT语句与FOREIGN KEY约束冲突
表和Coloums规格
主键表
产品分类
ProductCategoryID
外键表
SubProductCategory2 ProductCategoryID
在共ntroller我有以下几种方法创建子类时...
public ActionResult Create()
{
ViewBag.ProductCategory = db.ProductCategories.OrderBy(p =>
p.ProductCategoryID).ToList();
ViewBag.SubProductCategory2 = db.SubProductCategory2.OrderBy(a =>
a.ProductCategoryID).ToList();
var PC2 = new SubProductCategory2();
return View(PC2);
}
public ActionResult Create(SubProductCategory2 Createsubcat2,
FormCollection values)
{
if (ModelState.IsValid)
{
db.AddToSubProductCategory2(Createsubcat2);
db.SaveChanges();
//error pointing here and the full error message I am getting is...
/*error: System.Data.SqlClient.SqlException:
* The INSERT statement conflicted with the FOREIGN KEY constraint
* "FK_SubProductCategory2_ProductCategory". The conflict occurred in
* database "MyHouseDB", table "dbo.ProductCategory", column
* 'ProductCategoryID'. The statement has been terminated.*/
return RedirectToAction("/");
}
ViewBag.ProductCategory = db.ProductCategories.OrderBy(p =>
p.ProductCategoryID).ToList();
ViewBag.SubProductCategory2 = db.SubProductCategory2.OrderBy(a =>
a.ProductCategoryID).ToList();
return View(Createsubcat2);
}
ViewBag.ProductCategory = db.ProductCategories.OrderBy(p =>
p.ProductCategoryID).ToList();
ViewBag.SubProductCategory2 = db.SubProductCategory2.OrderBy(a =>
a.ProductCategoryID).ToList();
return View(Createsubcat2);
在我有以下代码的意见
...
<div class="editor-label">
@Html.LabelForModel()
</div>
<div class="editor-field">
@Html.DropDownList("CategoryName", new
SelectList((System.Collections.IEnumerable)ViewData["ProductCategory"],
"ProductCategoryID", "CategoryName"))
@Html.ValidationMessageFor(model => model.ProductCategory.CategoryName)
一些能告诉我该怎么解决INSERT语句与FOREIGN KEY约束错误消息冲突。纠正我,如果我错了,我有不正确地创建两个表之间的关系或其他问题在哪里?提前致谢。
严格来说2意味着1 ...这里的关系意味着“每个SubProductCategory属于一个ProductCategory”。 因此,如果不设置有效的productCategoryID,则无法创建SubProductCategory。这意味着ProductCategory必须已经存在于表中,所以您必须先创建它。 – Ben
是ProductCategory已经退出下拉列表中显示的内容。所以我在创建子类别时询问的问题是为什么从下拉菜单中选择值时数据不会被保存? – DiscoDude