無法保存多對多屬性到數據庫。對象具有相同的密鑰已經存在ObjectStateManager
錯誤細節:
具有相同鍵的對象已經存在於ObjectStateManager。 ObjectStateManager無法使用相同的 鍵追蹤多個對象。
我試圖財產保存在這個動作方法:
[HttpPost]
public ActionResult Edit(UserRole role)
{
var permissionNameList= (from per in _db.Permissions
select per.Name).Distinct().ToList();
foreach(var name in permissionNameList)
{
role.Permissions.Add(new permission(name, oper));
}
if (ModelState.IsValid)
{
_db.Entry(role).State = System.Data.EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(role);
}
數據庫表結構是這樣的:
3臺
userRole
- permissionsInRoles
- permission
CREATE TABLE newsmonitoringmanagement.permission
(
Id INT NOT NULL auto_increment,
Name VARCHAR (50) NOT NULL,
Description VARCHAR (250) NULL,
Operations INT NOT NULL,
PRIMARY KEY (Id),
UNIQUE KEY UK_permissionIdentity (Name, Operations)
);
在DB-方面:
modelBuilder.Entity<UserRole>()
.HasMany(usrRole => usrRole.Permissions)
.WithMany(permisn => permisn.Roles)
.Map(m =>
{
m.ToTable("permissionsInRoles");
m.MapLeftKey("RoleId");
m.MapRightKey("PermissionId");
});
modelBuilder.Entity<Permission>()
.HasMany(per => per.Roles)
.WithMany(role => role.Permissions)
.Map(m =>
{
m.ToTable("permissionsInRoles");
m.MapLeftKey("PermissionId");
m.MapRightKey("RoleId");
});
的更新,到這裏新的代碼可以工作, 但似乎有線,因爲ARG role
的permissions
屬性是empty
var permissionNameList = (from per in _db.Permissions
select per.Name).Distinct().ToList();
var realRole = (from r in _db.UserRoles
where r.Id == role.Id
select r).First();
foreach (var perm in realRole.Permissions)
{
var opert = Convert.ToInt32(Request.Form[perm.Name + "_op"]);
if (perm.Name.InList(permissionNameList))
{
perm.Operations = opert;
}
}
if (ModelState.IsValid)
{
_db.Entry(realRole).State = System.Data.EntityState.Modified;
_db.SaveChanges();
}
請參閱我的更新。 UNIQUE KEY UK_permissionIdentity(姓名,操作) –
我該怎麼辦? –
我已經更改了'Operations'屬性,所以我需要將所有這些事情都保存回數據庫。 var opert = Convert.ToInt32(Request.Form [name +「_op」]); –