在 EF Core 中过滤“包含”实体

Ром*_*кий 5 c# entity-framework-core asp.net-core

我有以下型号

 public class Person
{
    public int PersonId { get; set; }
    public string Name { get; set; }
    public List<PersonRole> PersonRoles { get; set; }

}

public class RoleInDuty
{
    public int roleInDutyId { get; set; }
    public string Name { get; set; }
    public int typeOfDutyId { get; set; }
    public TypeOfDuty typeOfDuty { get; set; }
    public List<PersonRole> PersonRoles { get; set; }

}
public class PersonRole
{
    public int PersonId { get; set; }
    public Person Person { get; set; }
    public int RoleInDutyId { get; set; }
    public RoleInDuty RoleInDuty { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

现在我可以使用以下代码加载所有人的所有角色:

 var  people = _context.Persons
      .Include(p => p.PersonRoles)
        .ThenInclude(e => e.RoleInDuty).ToList();
Run Code Online (Sandbox Code Playgroud)

但我不想将所有数据加载到 List,我需要根据输入的 typeOfDutyId 加载 PersonRole。我正在尝试使用以下代码解决此问题

people = _context.Persons
  .Include(p => p.PersonRoles
    .Where(t=>t.RoleInDuty.typeOfDutyId == Id)).ToList();
Run Code Online (Sandbox Code Playgroud)

但是VS抛出错误

InvalidOperationException: Include 属性 lambda 表达式 'p => {from PersonRole t in p.PersonRoles where ([t].RoleInDuty.typeOfDutyId == __typeOfDuty_typeOfDutyId_0) select [t]}' 无效。该表达式应表示属性访问:'t => t.MyProperty'。要定位在派生类型上声明的导航,请指定目标类型的显式类型化 lambda 参数,例如“(Derived d) => d.MyProperty”。有关包含相关数据的详细信息,请参阅http://go.microsoft.com/fwlink/?LinkID=746393

据我所知,我无法访问属性RoleInDuty.typeOfDutyId因为我还没有包含它。

我用下面的代码解决了这个问题

people = _context.Persons
  .Include(p => p.PersonRoles)
    .ThenInclude(e=>e.RoleInDuty).ToList();       
foreach (Person p in people)
{
  p.PersonRoles = p.PersonRoles
    .Where(e => e.RoleInDuty.typeOfDutyId == Id)
    .ToList();
}
Run Code Online (Sandbox Code Playgroud)

Ром*_*кий 2

devnull显示下一个如何在实体框架中过滤“包含”实体?,也有同样的问题,我读了它,并找到了答案。解决我的问题可以用下一个:

var temp = _context.Persons.Select(s => new
  {
    Person = s,
    PersonRoles= s.PersonRoles
      .Where(p => p.RoleInDuty.typeOfDutyId == this.typeOfDuty.typeOfDutyId)
      .ToList()
  }).ToList();
Run Code Online (Sandbox Code Playgroud)