関連すると思われる2つのテーブルがあります。MVC:INSERTステートメントがFOREIGN KEY制約と競合しました
テーブルと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つのテーブル間の関係を間違って作成しましたか?前もって感謝します。
厳密に言えば2は1を意味します。そこにある関係は、「各SubProductCategoryはProductCategoryに属します」という意味です。 有効なproductCategoryIDを設定せずにSubProductCategoryを作成することはできません。つまり、ProductCategoryはテーブルにすでに存在している必要があるため、最初に作成する必要があります。 – Ben
はいProductCategoryは既にドロップダウンリストに表示されています。ですから、私がSubCategoryを作成するときに質問するのは、ドロップダウンメニューから値を選択するときにデータが保存されないのはなぜですか? – DiscoDude