2012-10-29 198 views
0

當我試圖挽救這個模型中,menu.Roles場總是null,並保存更改方法不改變RolesEF:多到許多領域總是空

表是MenuRoleMenuRole

所以,我有一對許多-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")); 

回答

0

的ID從數據庫中檢索。那麼問題就解決了

,但我認爲這不是

[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"); 
    } 
0

我想這是因爲你要添加的角色,您的菜單,沒有菜單已附加到上下文。

嘗試的代碼更改爲

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"); 
+0

具有u曾經嘗試過的最好的解決辦法?仍然爲空。 –