使用ASP.NET MVC 3中的实体框架更新引用
我已经定义了以下两个类:
public class User
{
    public System.Guid UserId { get; set; }
    public System.Guid? ContactId { get; set; }
    public string UserName { get; set; }
    public virtual Contact Contact { get; set; }
}
public class Contact
{
public System.Guid ContactId { get; set; }
    public string PhoneNumber { get; set; }
}
下面是映射:
this.HasOptional(u => u.Contact)
.WithMany()
.HasForeignKey(u => u.ContactId);
我在MVC 3中定义了一个编辑页面来更新用户信息,该页面包含用户的属性+用户的联系人属性:
<div class="editor-field">
@Html.EditorFor(model => model.UserName)
@Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Contact.PhoneNumber)
@Html.ValidationMessageFor(model => model.Contact.PhoneNumber)
</div>
并且在控制器的post方法中:
[HttpPost]
public ActionResult Edit(User user)
{
    if (ModelState.IsValid)
    {
        context.Entry(user).State = EntityState.Modified;
        context.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(user);
}
  但是这抛出: 
 A referential integrity constraint violation occurred: The property values that define the referential constraints are not consistent between principal and dependent objects in the relationship.  在行中: context.Entry(user)... 
  这种例外的原因是什么?  以及如何更新用户和联系人实体,而不会在MVC 3中彼此冲突? 
  谢谢。 
  你在页面的隐藏字段中有User.ContactId和User.Contact.ContactId属性并将它们发回吗?  我认为,除了说,主键属性User.Contact.ContactId的Contact (委托人)不具有相同的值作为外键值User.ContactId的User (因)。  这些是“定义参考约束的属性值”,它们“不一致”。 
  BTW:在context.Entry(user).State = EntityState.Modified中将状态设置为Modified 。仅影响user实体的标量属性和复杂属性。  如果您的视图的用户也可能更改了Contact数据(导航属性),则您必须将此实体的状态设置为已Modified : 
context.Entry(user).State = EntityState.Modified;
context.Entry(user.Contact).State = EntityState.Modified;
上一篇: Updating references using entity framework in ASP.NET MVC 3
下一篇: ASP.NET MVC save new record verse update existing record conventions
