2011-03-12 19 views
0

関連すると思われる2つのテーブルがあります。MVC:INSERTステートメントがFOREIGN KEY制約と競合しました

enter image description here

テーブルとColoums仕様

プライマリキーテーブル
ProductCategory
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); 

を以下のメソッドを持っていntroller ...

<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つのテーブル間の関係を間違って作成しましたか?前もって感謝します。

答えて

0

私はこの問題を発見しました。私のSQLデータベース設計ではなく、MVC側でコーディングしていました。 SubCategoryテーブルからCategoryName列を削除しました。 Allow Nullがtrueに設定されている限り、CategoryNameを感じることができました。 PrimaryKeyが2つのテーブルに対して正しく設定されていることには何の意味もありませんでした。

1

このエラーは、次の条件が当てはまる場合に発生します。1) "ProductCategoryID"で選択した値が "ProductCategory"テーブルに存在しないか、2)製品カテゴリテーブルが空です。

商品カテゴリテーブルに値がありますか?

ProductCategoryIDにはどのような価値がありますか?

+0

厳密に言えば2は1を意味します。そこにある関係は、「各SubProductCategoryはProductCategoryに属します」という意味です。 有効なproductCategoryIDを設定せずにSubProductCategoryを作成することはできません。つまり、ProductCategoryはテーブルにすでに存在している必要があるため、最初に作成する必要があります。 – Ben

+0

はいProductCategoryは既にドロップダウンリストに表示されています。ですから、私がSubCategoryを作成するときに質問するのは、ドロップダウンメニューから値を選択するときにデータが保存されないのはなぜですか? – DiscoDude

関連する問題