【发布时间】: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