簡體   English   中英

如何過濾和 select 一個 List 是一個 class LINQ 的屬性?

[英]How to filter and select a List that is an attribute of a class LINQ?

我有Privilege

public class Privilege
{
   public virtual string Name { get; set; }
   public virtual ICollection<Role> Roles { get; set; } = new List<Role>();

}

我有一個 Role,它包含一個Privilege集合和一個對應的UserType ,該 UserType 屬於該Privilege

public class Role
{
    public virtual ICollection<Privilege> Privileges { get; set;} = new List<Privilege>();
    public virtual UserType UserType { get; set;}
}

我正在嘗試從僅包含具有我傳遞的RolePrivileges的特權回購中獲取List<Privilege> 我的問題有點令人困惑,因為這兩個類都有另一個類的集合,而且這個代碼庫非常像意大利面條,無法更改。

這是我的嘗試,問題是我實際上無法獲得List<Privilege>而是取回這個瘋狂的IQueryable<IEnumerable<ICollection<Privilege>>>變量。

_privRepo.Query().Select(p => p.Roles.ToList().Where(r => r.UserType == UserType.Manager).Select(x => x.Privileges);

假設_privRepo是一個 entityFramework DbContext,我會說這樣的事情應該可以解決問題:

var privileges = _privRepo.Where(p => p.Roles.Any(r => r.UserType == UserType.Manager)).ToList();

或異步版本

var privileges = await _privRepo.Where(p => p.Roles.Any(r => r.UserType == UserType.Manager)).ToListAsync();

你必須重構你的代碼,如果它是多對多關系那么應該有另一個 class 來建立它們之間的關系。

https://learn.microsoft.com/en-us/ef/core/modeling/relationships

盡管您找到了查詢的解決方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM