我正在尝试添加一个包含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 .....
答案 0 :(得分:0)
在模型的AddUser
中,您创建了一个新的KebaContext
并添加了user
,但user.Role
看起来包含来自不同的Role
上下文。