[英]EF: many-to-many field always null
when i try to save this model, the menu.Roles
field is always null
, and save change method doesn't change the Roles
field 当我尝试保存此模型时,
menu.Roles
字段始终为null
,并且save change方法不会更改Roles
字段
tables are Menu
, RoleMenu
and Role
表格是
Menu
, RoleMenu
和Role
so, i have a pair many-2-many models: 因此,我有一对多2到许多模型:
Menu has a Roles
filed 菜单中有
Roles
Role has a Menus
fields 角色具有“
Menus
字段
action method: 动作方法:
[HttpPost]
public ActionResult Edit(Menu menu, IEnumerable<int> RoleIDs)
{
if (ModelState.IsValid)
{
var roles = _db.UserRoles.Where(rl => RoleIDs.Contains(rl.Id)).ToList();
menu.Roles = new List<UserRole>();
menu.Roles.AddRange(roles);
_db.Entry(menu).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ParentMenuId = new SelectList(_db.Menus, "Id", "Name", menu.ParentMenuId);
ViewBag.RoleIDs = new SelectList(_db.UserRoles.ToList(), "Id", "Name");
return View(menu);
}
view: 视图:
//...other VS auto generated fields...
<div class="editor-label">
@Html.LabelFor(model => model.Roles, "Roles")
</div>
<div class="editor-field">
@Html.ListBox("RoleIDs")
@Html.ValidationMessageFor(model => model.Roles)
</div>
<p>
<input type="submit" value="Save" />
</p>
mapping: 映射:
modelBuilder.Entity<Role>()
.HasMany(role => role.Menus)
.WithMany(menu => menu.Roles)
.Map(m =>
m.MapLeftKey("RoleId").
MapRightKey("MenuId").
ToTable("RoleMenu"));
I think this is because you are adding the roles to your menu, without the menu having been attached to the context. 我认为这是因为您要在菜单中添加角色,而没有将菜单附加到上下文中。
Try changing the code to 尝试将代码更改为
var roles = _db.UserRoles.Where(rl => RoleIDs.Contains(rl.Id)).ToList();
_db.Attach(menu);
menu.Roles = new List<UserRole>();
menu.Roles.AddRange(roles);
_db.SaveChanges();
return RedirectToAction("Index");
retrieve it from db by id. 通过ID从数据库检索它。 then problem solved
然后问题解决了
but i think this is not the best solution 但是我认为这不是最好的解决方案
[HttpPost]
public ActionResult Edit(Menu menu, IEnumerable<int> RoleIDs)
{
var menuReal = (from m in _db.Menus.Include("Roles")
where m.Id == menu.Id
select m).FirstOrDefault();
var roles = _db.UserRoles.Where(rl => RoleIDs.Contains(rl.Id)).ToList();
menuReal.Roles = roles;
_db.Entry(menuReal).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.