MVC:INSERT语句与FOREIGN KEY约束冲突

时间:2011-03-12 15:23:01

标签: database asp.net-mvc-2 foreign-keys

我有两张应该相关的表。

enter image description here

表和Coloums规范

主键表
产品分类
ProductCategoryID

外键表
SubProductCategory2 ProductCategoryID

在控制器中,我在创建子类别时有以下方法......

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)

有些人可以告诉我如何解决与FOREIGN KEY约束错误消息冲突的INSERT语句。纠正我,如果我错了,我是否错误地创建了两个表之间的关系或其他问题在哪里?提前致谢。

2 个答案:

答案 0 :(得分:1)

如果满足以下条件,则会发生此错误1)“ProductCategory”中为“ProductCategory”选择的值不存在于“ProductCategory”表中或2)产品类别表为空。

您是否在产品类别表中包含值?

您为ProductCategoryID选择了什么值?

答案 1 :(得分:0)

我发现了这个问题。这是我的sql数据库设计而不是MVC编码方面。我从SubCategory表中删除了CategoryName列。只要Allow Null设置为true,我就能感受到CategoryName。没有必要这样做,已经为两个表正确设置了PrimaryKey。

相关问题