MVC 3 EF - 使用现有数据添加新记录
问题描述:
我有一个带两张表的发票和客户。客户PK在发票表中是FK。我有一个创建视图,用户在其中填写发票数据。在这个表单中,我有一个带有SelectList的@ Html.DropDownList,其中填充了db客户中已经存在的名称。用户选择客户数据字段的基础是autopopulated客户数据经由局部视图数据库:MVC 3 EF - 使用现有数据添加新记录
@using (Ajax.BeginForm("CustomerSelect", "Invoice", new AjaxOptions{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "CustomerFields"}))
这工作得很好,但是当我创建提交按钮,它会在该CUTOMER的新实例数据库,即使它应该使用从数据库检索到的ID。当被显示在创建视图的局部视图它里显示正确客户ID:
<div class="editor-label">
@Html.LabelFor(model => model.Customer)
<div class="editor-field">
@Html.EditorFor(model => model.Customer)
@Html.ValidationMessageFor(model => model.Customer)
</div>
</div>
但是,当我看发票对象内部中的Controler的httppost创建方法它显示了示出了一个不同的(新)客户ID:
[HttpPost]
public ActionResult Create(Invoice invoice)
{
if (ModelState.IsValid)
{
db.Invoices.Add(invoice); **//invoice.Customer.CustomerID == 1**
db.SaveChanges(); **//invoice.Customer.CustomerID changes to next free in the db == 7**
return RedirectToAction("Index");
}
return View(invoice);
}
我在做什么错?
答
Add
方法增加了实体图中的所有实体。因此,如果您的发票实例具有Customer
属性集,并且您打电话添加,它将为客户和发票创建新记录。
如果你想只添加发票您有几种选择:
- 揭露发票
CustomerID
,不与导航性能运行。这将为您提供foreign key association,这在这种情况下更容易使用。 - 将客户实例的状态更改回原来的状态,以便只将发票和客户之间的发票和关系视为已添加。
例子:
db.Invoices.Add(invoice);
db.Entry(invoice.Customer).State = EntityState.Unchanged;
db.SaveChanges();
这两种方式对我的工作太好了,谢谢了很多! – Eric 2012-03-23 13:06:10