如何使用LINQ限制Included类中的数据?

时间:2014-11-22 09:15:48

标签: c# asp.net linq entity-framework asp.net-identity

我有两个ASP.NET标识使用的类。一个是用户列表的支持类,另一个是角色。在数据库中有三个表。 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);

1 个答案:

答案 0 :(得分:2)

<{3}}的

参数是

  

谓词
  键入:System.Linq.Expressions.Expression&lt; Func&lt; TSource,Boolean&gt;&gt;

  用于测试条件的每个元素的函数。

因此您需要传递一个返回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
      )