我有三张表如下:
public class A {
public int A_ID {get;set;}
...
}
public class B {
public int B_ID {get;set;}
...
}
public class C {
public int A_ID {get;set;}
public int C_B_ID {get;set;}
...
public virtual A a {get;set;}
public virtual B b {get;set;}
}
我设置了以下按键:
modelBuilder.Entity<C>()
.HasRequired(x => x.a)
.WithMany()
.HasForeignKey(u => u.A_ID);
modelBuilder.Entity<C>()
.HasRequired(x => x.b)
.WithMany()
.HasForeignKey(u => u.C_B_ID);
modelBuilder.Entity<C>()
.Property(t => t.A_ID)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
在“创建视图”页面上,我有以下外键的下拉列表:
<div class="editor-label">
@Html.LabelFor(model => model.A_ID, "A")
</div>
<div class="editor-field">
@Html.DropDownList("A_ID", String.Empty)
@Html.ValidationMessageFor(model => model.A_ID)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.C_B_ID, "B")
</div>
<div class="editor-field">
@Html.DropDownList("C_B_ID", String.Empty)
@Html.ValidationMessageFor(model => model.C_B_ID)
</div>
这是我的创建功能:
//
// GET: /C/Create
public ActionResult Create()
{
ViewBag.A_ID = new SelectList(db.As, "A_ID", "Name");
ViewBag.B_ID = new SelectList(db.Bs, "B_ID", "Name");
return View();
}
//
//POST
public ActionResult Create(C c_instance)
{
if (ModelState.IsValid)
{
db.Cs.Add(c_instance);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.A_ID = new SelectList(db.As, "A_ID", "Name", c_instance.A_ID);
****EDITED*** ViewBag.B_ID = new SelectList(db.Bs, "B_ID", "Name", c_instance.C_B_ID);
return View(c_instance);
}
现在,在create函数中,我收到在A_ID的第一个下拉列表中选择的值,但C_B_ID的下拉值始终为零。这导致了这个问题:
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_dbo.Cs_dbo.Bs_C_B_ID".
The conflict occurred in database "C:\temp.MDF", table "dbo.Bs", column 'B_ID'.
The statement has been terminated.
现在,这种情况正在发生,因为C_instance.A_ID具有从下拉列表中选择的正确A_ID,但始终是C_instance.C_B_ID = 0! (并且下拉列表会显示表B中的所有条目,我选择其中一个)
导致这种情况的原因是什么?
答案 0 :(得分:0)
您需要将列表传递给DropDownList
帮助程序。
@Html.DropDownList("A_ID", ViewBag.A_ID, String.Empty)
@Html.DropDownList("C_B_ID", ViewBag.B_ID, String.Empty)