我有两个类被 ASP.NET Identity使用。一个是用户列表的支持类,另一个具有角色。数据库中有三个表。AspNetUsers、AspNetRoles 和 AspNetUserRoles。由于它们在实体框架中的映射方式,这三个类仅映射到两个类:
public partial class AspNetUser
{
public AspNetUser()
{
this.AspNetUserClaims = new List<AspNetUserClaim>();
this.AspNetUserLogins = new List<AspNetUserLogin>();
this.AspNetRoles = new List<AspNetRole>();
}
public int Id { get; set; }
public virtual ICollection<AspNetRole> AspNetRoles { get; set; }
public virtual ICollection<AspNetUserClaim> AspNetUserClaims { get; set; }
public virtual ICollection<AspNetUserLogin> AspNetUserLogins { get; set; }
}
和
public partial class AspNetRole
{
public AspNetRole()
{
this.AspNetUsers = new List<AspNetUser>();
}
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<AspNetUser> AspNetUsers { get; set; }
}
有人可以告诉我如何创建一个 LINQ 语句来检索具有特定角色类型的所有用户,或者如果我提供的 roleId 为零,那么我希望看到所有用户而不是限制 roleId。 这是我尝试过的:
var user = await db.AspNetUsers
.Where(u => u.AspNetRoles.SelectMany(r => r.Id == roleId || roleId == 0))
.Include(u => u.AspNetRoles);
我也试过:
var user = await db.AspNetUsers
.Where(u => u.AspNetRoles.Select(r => r.Id == roleId || roleId == 0))
.Include(u => u.AspNetRoles);
where is 的参数
谓语
类型:System.Linq.Expressions.Expression<Surce,布尔值>>
用于测试每个元素的条件的函数。
所以你需要传递一个返回bool
的函数,比如
.Where(u => roleId == 0 //if roleId is 0 return all
|| u.AspNetRoles.Any(r => r.Id == roleId) // check that user have any roles with id equals to roleId
)