无法创建类型' WebApplication2.Models.Role'的常量值。在此上下文中仅支持基元类型或枚举类型

时间:2015-05-09 14:24:44

标签: c# asp.net-mvc linq

[HttpGet]
public ActionResult Edit(int id)
{
    var userToEdit = _db.AuthLogin.Where(user => user.Id == id).SingleOrDefault();
    if (userToEdit == null)
        return HttpNotFound();


    return View(new EditUser()
    {
        Email = userToEdit.Email,
        UserName = userToEdit.UserName,
        Password = userToEdit.Password,
        Roles = _db.Roles.Select(role => new RoleCheckBox
        {
            Id = role.Id,
            IsChecked = userToEdit.Roles.Contains(role),
            Name = role.Name
        }).ToList()
    });
}

1 个答案:

答案 0 :(得分:0)

我不知道你的Role课是如何定义的,但你可以尝试这样的事情:

    List<int> userRoleIds = userToEdit.Roles.Select(r => r.Id).ToList();
    EditUser model = new EditUser()
    {
        Email = userToEdit.Email,
        UserName = userToEdit.UserName,
        Password = userToEdit.Password,
        Roles = _db.Roles.Select(role => new RoleCheckBox
        {
            Id = role.Id,
            IsChecked = userRoleIds.Contains(role.Id),
            Name = role.Name
        }).ToList()
    });
    return View(model);

或更改

_db.Roles.Select(...)

_db.Roles.ToList().Select(...)