无法将多对多属性保存到数据库。
错误明细:
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-context中的:
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
的{{1}}属性为permissions
empty
答案 0 :(得分:0)
name field
是权限表中的唯一字段吗?
如果是,那么显然你不能使用与前一个name
相同的var permissionList= (from per in _db.Permissions
select per).Distinct();
foreach(var permission in permissionList)
{
var opert = Convert.ToInt32(Request.Form[name + "_op"]);
//var per=new Permission();
//per.Name=name;
permmission.Operations=opert;
role.Permissions.Add(permission);
}
来获得新的许可,这就是你在做什么。
编辑: - 你只是添加你从数据库获得的权限,因为它是
我的意思是确实需要创建新的许可
像这样的事情
{{1}}
答案 1 :(得分:0)
从数据库中检索的模式代码然后它可以工作。
public ActionResult Edit(UserRole role)
{
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();
}
this.TempData["msg"] = "[EditRolePermissions]Saved Role Id " + role.Id;
return RedirectToAction("Details/" + role.Id);
}