I am working with an edit user view that includes First name, Last Name, Username, etc.
I am also incorporating IsApproved and IsLockedOut from the Membership table in this edit user view as well.
See code snippet:
//Username from User table
<div class="editor-label">
@Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
@Html.DisplayFor(model => model.UserName)
@Html.ValidationMessageFor(model => model.UserName)
</div>
//IsApproved from Membership table
<div class="editor-label">
@Html.LabelFor(model => model.aspnet_Membership.IsApproved)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.aspnet_Membership.IsApproved)
@Html.ValidationMessageFor(model => model.aspnet_Membership.IsApproved)
</div>
I can go to edit the user, but when I try to save the changes, the following comes up:
"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."
and takes place with the following code: db.Users.Attach(user); where user is passed into the method Edit in the controller.
No errors occur when I take away the code associated with the Membership table.
How do I go about resolving this issue? Is there a better approach?
UPDATE: Here’s what’s going on in the controller (in a nutshell):
public ActionResult Edit(int id)
{
User user = db.Users.Single(u => u.UserID == id);
ViewBag.UserGUID = new SelectList(db.Memberships, "UserId", "Password", user.UserGUID);
ViewBag.CompanyID = new SelectList(db.Companies, "CompanyID", "CompanyName", user.CompanyID);
return View(user);
}
public ActionResult Edit(User user)
{
if (ModelState.IsValid)
{
db.Users.Attach(user);
db.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);
db.SaveChanges();
}
ViewBag.UserGUID = new SelectList(db.Memberships, "UserId", "Password", user.UserGUID);
ViewBag.CompanyID = new SelectList(db.Companies, "CompanyID", "CompanyName", user.CompanyID);
return View(user);
}
I would create a model with all the properties you need, so you can use it in the view. Then you can separate your data operations between the different tables.
It’s not as short in the code as doing the Attach(), but it should allow more fine-grained control over your data operations.