0
當我試圖挽救這個模型中,menu.Roles
場總是null
,並保存更改方法不改變Roles
場EF:多到許多領域總是空
表是Menu
,RoleMenu
和Role
所以,我有一對許多-2-許多型號:
菜單有一個Roles
申請
角色有一個Menus
個領域
操作方法:
[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);
}
觀點:
//...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>
映射:
modelBuilder.Entity<Role>()
.HasMany(role => role.Menus)
.WithMany(menu => menu.Roles)
.Map(m =>
m.MapLeftKey("RoleId").
MapRightKey("MenuId").
ToTable("RoleMenu"));
具有u曾經嘗試過的最好的解決辦法?仍然爲空。 –