保存新模型对象时出现InvalidOperationException

时间:2015-05-13 15:07:31

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

我正在尝试添加一个包含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 .....

1 个答案:

答案 0 :(得分:0)

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