从控制器中的其他数据库表更改字段

时间:2012-03-16 16:31:43

标签: c# asp.net-mvc razor

我正在使用包含First name, Last Name, Username, etc.

的修改用户视图

我也在此编辑用户视图中的Membership表中合并了IsApprovedIsLockedOut

请参阅代码段:

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

我可以去编辑用户,但是当我尝试保存更改时,会出现以下内容:

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

并使用以下代码进行操作:db.Users.Attach(user);其中user传递到控制器中的方法Edit

当我拿走与Membership表相关联的代码时,不会发生错误。

如何解决此问题?有更好的方法吗?

更新:以下是控制器中发生的事情(简而言之):

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

1 个答案:

答案 0 :(得分:0)

我会创建一个包含您需要的所有属性的模型,因此您可以在视图中使用它。然后,您可以在不同的表之间分离数据操作。

public ActionResult Edit(int id)
{
    User user = db.Users.Single(u => u.UserID == id);
    UserViewModel model = new UserViewModel()
    {
        UserID = user.UserID,
        //etc.
    }

    ViewBag.UserGUID = new SelectList(db.Memberships, "UserId", "Password", user.UserGUID);
    ViewBag.CompanyID = new SelectList(db.Companies, "CompanyID", "CompanyName", user.CompanyID);

    return View(model);
} 

public ActionResult Edit(UserViewModel userModel)
{
    if (ModelState.IsValid)
    {
        // Update user properties
        User user = db.Users.Single(u => u.UserID == userModel.UserID);
        // etc.

        // If you need to update the membership value, do that next

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

它在代码中并不像执行Attach()那样短,但它应该允许对数据操作进行更精细的控制。