如何使用 LINQ 查询加入枚举

Kir*_*irk 2 c# linq asp.net enums

我有用户表(来自IdentityUserASP.CORE 的默认 ApplicationUser 表),并且我为 RoleType 添加了附加字段。我还添加了一个 Enum 来指定角色定义。

public enum Roles
{
    Administrator = 1,
    Headquarters = 2,
    Branch = 3,
    Driver = 4,
    Client = 5
}
Run Code Online (Sandbox Code Playgroud)

现在我想将视图中的所有用户显示为表格以及角色描述。

我无法使用 LINQ 连接对 Enum 和用户表进行 LINQ 查询。

Ste*_*ord 5

要从枚举中获取角色列表,请使用:

var roles = Enum.GetValues(typeof(Roles)).Cast<Roles>()
        .Select(r => new { Value = (int)r, Name = r.ToString() }).ToList();
Run Code Online (Sandbox Code Playgroud)

然后你可以在你的 Linq 查询中使用它,例如:

var roles = Enum.GetValues(typeof(Roles)).Cast<Roles>()
        .Select(r => new { Value = (int)r, Name = r.ToString() }).ToList();

var users = from u in ApplicationUser
        join r in roles on u.Role equals r.Value
        select new {Name = u.Name, RoleId = u.Role, RoleDescription = r.Name} ;
Run Code Online (Sandbox Code Playgroud)

没有的更简单的方法Enum.GetValues是:

var users = from u in ApplicationUser
        select new {Name = u.Name, RoleId = u.Role, RoleDescription = (Roles)r.Role.ToString()} ;
Run Code Online (Sandbox Code Playgroud)