Updating references using entity framework in ASP.NET MVC 3

I have defined the following two classes:

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

And below is the mapping:

this.HasOptional(u => u.Contact)
.WithMany()
.HasForeignKey(u => u.ContactId);

I have defined an edit page in MVC 3 to update user info, the page contains user's properties + user's contact properties:

<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>

And in the controller's post method:

[HttpPost]
public ActionResult Edit(User user)
{
    if (ModelState.IsValid)
    {
        context.Entry(user).State = EntityState.Modified;
        context.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(user);
}

But this throws:
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. in line: context.Entry(user)... .

What's the cause of this exception? and how can I update User and contact entities without conflicting each other in MVC 3?
Thank you.


Do you have the User.ContactId and User.Contact.ContactId properties in hidden fields on the page and post them back? I believe that the exception says that the primary key property User.Contact.ContactId of Contact (the principal) does not have the same value as the foreign key value User.ContactId of User (the dependent). These are "the property values that define the referential constraints" and they "are not consistent".

BTW: Setting the state to Modified in context.Entry(user).State = EntityState.Modified only affects the scalar and complex properties of the user entity. If the user of your view could also have changed the Contact data (a navigation property) you must set the state of this entity to Modified as well:

context.Entry(user).State = EntityState.Modified;
context.Entry(user.Contact).State = EntityState.Modified;
链接地址: http://www.djcxy.com/p/25470.html

上一篇: 保存父实体时,包含的集合的模型更新没有保存在数据库中?

下一篇: 使用ASP.NET MVC 3中的实体框架更新引用