두 테이블이 관련되어 있습니다.MVC : INSERT 문이 FOREIGN KEY 제약 조건과 충돌했습니다.
테이블과 Coloums 사양
기본 키 테이블
ProductCategory
ProductCategoryID
외래 키 테이블 공동으로
SubProductCategory2 ProductCategoryID
하위 카테고리를 만들 때 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)
이 어떤 방법을 해결하는 말해 수 ... 나는 다음과 같은 코드를 가지고있는 뷰에서
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);
... 다음과 같은 방법을 INSERT 문이 FOREIGN KEY 제약 조건 오류 메시지와 충돌했습니다. 내가 틀렸다면 나를 정정하십시오. 두 테이블 사이의 관계를 잘못 작성했거나 다른 곳에 문제가 있습니까? 미리 감사드립니다.
엄밀히 말하면 2는 1을 의미합니다 ... 거기에는 "각 SubProductCategory는 ProductCategory에 속합니다"라는 의미입니다. 유효한 productCategoryID를 설정하지 않고 SubProductCategory를 만들 수 없습니다. 즉, ProductCategory가 테이블에 이미 있어야하므로 먼저 카탈로그를 만들어야합니다. – Ben
예 ProductCategory가 이미 드롭 다운 목록에 표시됩니다. 그래서 하위 카테고리를 만들 때 묻는 질문은 드롭 다운 메뉴에서 값을 선택할 때 데이터가 저장되지 않는 이유는 무엇입니까? – DiscoDude