当我在编辑视图中更改所有属性然后点击"保存"时,数据库只更新所有简单属性,如整数和字符串。 但是,我的模型是" User"并且用户有一个" Permission"并且可以有多个"角色"。这些也是类,它们只是随着更新而改变。
我正在使用此UserViewModel(强烈输入编辑视图):
public class UserViewModel
{
AuditDB db = new AuditDB();
/// <summary>
/// Constructor for an empty userviewmodel, without a user
/// </summary>
public UserViewModel()
{
AllRoles = db.Roles.ToList();
UserRoles = new List<Role>();
User = new User();
User.Roles = new List<Role>();
SelectedRoleIds = UserRoles.Select(x => x.Id).ToArray();
}
/// <summary>
/// Constructor for a userviewmodel with an already existing user
/// </summary>
/// <param name="userId"></param>
public UserViewModel(int userId)
{
AllRoles = db.Roles.ToList();
User = db.Users.Single(user => user.Id == userId);
UserRoles = User.Roles.ToList();
SelectedRoleIds = UserRoles.Select(x => x.Id).ToArray();
}
public User User { get; set; }
public List<Role> AllRoles { get; set; }
public List<Role> UserRoles { get; set; }
public int[] SelectedRoleIds { get; set; }
}
控制器(我认为错误在哪里)看起来像这样:
[HttpPost]
public ActionResult Edit(UserViewModel model)
{
if (ModelState.IsValid)
{
model.User.Permission = db.Permissions.Single(p => p.Id == model.User.Permission.Id);
model.User.Roles = new List<Role>();
foreach (int roleId in model.SelectedRoleIds)
{
model.User.Roles.Add(db.Roles.Single(role => role.Id == roleId));
}
model.User.LastUpdate = DateTime.Now;
db.Entry(model.User).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(model);
}
奖励问题:我在UserViewModel中实例化我的AuditDB(:DbContext)类,以从那里访问所有角色的列表。这是放置ViewModel或不应该在ViewModel中执行此操作的正确位置吗?
先谢谢你的帮助;)