gpt4 book ai didi

c# - 如何使用 LINQ 限制来自包含类的数据?

转载 作者:太空宇宙 更新时间:2023-11-03 10:37:30 24 4
gpt4 key购买 nike

我有两个由 ASP.NET Identity 使用的类。一个是用户列表的支持类,另一个具有角色。在数据库中有三个表。 AspNetUsers、AspNetRoles 和 AspNetUserRoles。由于它们在 Entity Framework 中的映射方式,这三个映射到两个类:

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 的参数是

predicate
Type: System.Linq.Expressions.Expression<Func<TSource, Boolean>>
A function to test each element for a condition.

所以你需要传递一个返回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
)

关于c# - 如何使用 LINQ 限制来自包含类的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27075810/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com