0

我有三个表如下:

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);
    }

现在,在创建函数中,我收到在第一个下拉列表中为 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!(下拉列表确实显示了表 Bs 中的所有条目,我选择其中一个)

这可能是什么原因造成的?

4

1 回答 1

0

您需要将您的列表传递给DropDownList助手。

@Html.DropDownList("A_ID", ViewBag.A_ID, String.Empty)
@Html.DropDownList("C_B_ID", ViewBag.B_ID, String.Empty)
于 2013-08-29T19:27:18.103 回答