2011-03-12 109 views
0

我有两个应该是相关的表。MVC:INSERT语句与FOREIGN KEY约束冲突

enter image description here

表和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约束错误消息冲突。纠正我,如果我错了,我有不正确地创建两个表之间的关系或其他问题在哪里?提前致谢。

回答

0

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

1

当以下条件为真时,会发生此错误1)您为“ProductCategoryID”选择的值不在“ProductCategory”表中或2)产品类别表为空。

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

您为ProductCategoryID选择了什么值?

+0

严格来说2意味着1 ...这里的关系意味着“每个SubProductCategory属于一个ProductCategory”。 因此,如果不设置有效的productCategoryID,则无法创建SubProductCategory。这意味着ProductCategory必须已经存在于表中,所以您必须先创建它。 – Ben

+0

是ProductCategory已经退出下拉列表中显示的内容。所以我在创建子类别时询问的问题是为什么从下拉菜单中选择值时数据不会被保存? – DiscoDude

相关问题