【问题标题】:InvalidOperationException while saving a new model object保存新模型对象时出现 InvalidOperationException
【发布时间】:2015-05-13 15:07:31
【问题描述】:

我正在尝试添加一个新的User(型号),其中包括一个Role(型号)。 我的视图包括一个DropDownListFor,其中包含一个角色列表。 尝试最终将用户添加到数据库时,我总是遇到异常。

查看:

@model Keba.Data.EF.User
@{
    ViewBag.Title = "Add User";
    List<SelectListItem> roles = new List<SelectListItem>();

}
<h2>Add</h2>
@using (Html.BeginForm("AddUser", "User", FormMethod.Post,
                                      new { enctype = "multipart/form-data" }))
{
    <table>
        <tr><th>@Html.LabelFor(model => model.UserName)</th><td>@Html.EditorFor(model => model.UserName)</td></tr>
        <tr><th>@Html.LabelFor(model => model.Password)</th><td>@Html.EditorFor(model => model.Password)</td></tr>
        @Html.HiddenFor(model => model.MailAdress)
        <tr>
            <th>Roles</th>
            <td>
               @Html.DropDownListFor(x => x.Role.RoleId, new SelectList(ViewBag.roles, "RoleId", "RoleName"))

            </td>
        </tr>
    </table>
    <input name="add" type="submit" value="add" />
    <input name="cancel" type="submit" value="cancel" />
}

控制器:

 [HttpPost]
 public ActionResult AddUser(User user)
 {
     if (Request.Form["add"] != null)
     {
         user.Role = RoleModel.Instance.getRoles().Where(x => x.RoleId == user.Role.RoleId).FirstOrDefault();
         UserModel.Instance.AddUser(user);
     }
     return RedirectToAction("Index");
 }

型号:

public void AddUser(User user)
{
    using(var db = new KebaContext())
    {
        if (user != null)
        {
            user.MailAdress = "";
            db.UserSet.Add(user);//Exception
            db.SaveChanges();
        }             
    }
}

例外:

{System.InvalidOperationException: An entity object cannot be referenced by multiple instances of IEntityChangeTracker.
   at System.Data.Entity.Core.Objects.ObjectContext.VerifyContextForAddOrAttach(IEntityWrapper wrappedEntity)
   at .....

【问题讨论】:

  • 您是如何定义Roles 和Users 的?没有一对一的关系吗?
  • 它们被定义为 1-*,它们是由模型设计器(实体框架)imgur.com/5kuTrMJ 创建的
  • 你有没有机会在 github 上得到这个,以便我们更好地调试这个问题?
  • RoleModel 和 UserModel 是否共享相同的数据库上下文?当实体不共享相同的数据库上下文但您从一个上下文中获取对象并尝试在另一个上下文中使用它(将角色应用于用户)时,可能会发生此错误。

标签: c# asp.net-mvc-4 razor entity-framework-6


【解决方案1】:

在模型的AddUser 中,您正在创建一个新的KebaContext 并添加user,但user.Role 看起来它包含来自不同上下文的Role

【讨论】:

  • 没有其他上下文,只有 KebaContext。
  • 对不起,我的意思是,看起来您正在从 KebaContext 的一个实例中检索 Role(在 getRoles() 中?),那么当您添加用户时,您'将其添加到KebaContext 的新实例中,该实例尝试将任何关联实体附加到该上下文。您可能需要确保先前的上下文已被释放。
猜你喜欢
  • 1970-01-01
  • 2014-06-15
  • 2021-02-02
  • 1970-01-01
  • 2014-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多