c# - 在 EF Core 中过滤 "include"实体

标签 c# asp.net-core entity-framework-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; }
}

现在我可以使用以下代码加载所有人的所有角色:
 var  people = _context.Persons
      .Include(p => p.PersonRoles)
        .ThenInclude(e => e.RoleInDuty).ToList();

但我不想将所有数据加载到 List,我需要根据输入的 typeOfDutyId 加载 PersonRole。
我正在尝试使用以下代码解决此问题
people = _context.Persons
  .Include(p => p.PersonRoles
    .Where(t=>t.RoleInDuty.typeOfDutyId == Id)).ToList();

但是VS抛出错误

InvalidOperationException: The Include property lambda expression 'p => {from PersonRole t in p.PersonRoles where ([t].RoleInDuty.typeOfDutyId == __typeOfDuty_typeOfDutyId_0) select [t]}' is invalid. The expression should represent a property access: 't => t.MyProperty'. To target navigations declared on derived types, specify an explicitly typed lambda parameter of the target type, E.g. '(Derived d) => d.MyProperty'. For more information on including related data, see 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();
}

最佳答案

devnull显示下一个 How to filter "Include" entities in entity framework? ,并且有同样的问题,我阅读了它,并找到了答案。解决我的问题可以用下一个:

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

关于c# - 在 EF Core 中过滤 "include"实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54374565/

相关文章:

c# - 专门针对旧版本的单个 .NET Standard API/命名空间(Entity Framework Core)

c# - 如何使用 EF Core 2.2 将 JSON_VALUE 转换为 DateTime?

c# - 如何仅使用 XPath 和 C# .NET 获取元素内容

c# - MVC Controller 的 HttpContext 为空

c# - 如何使用 System.Data.SQLite.Linq

asp.net-core - 为什么DistributedCache SessionHandler抛出连接问题?

c# - 拆分字符串时使用十六进制作为分隔符

asp.net-core - 失败 : Microsoft. AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]

asp.net - 在 azure 上的 asp.net vnext 网站上禁用端口 80

c# - Azure 不会在发布 EFCore 2 应用程序时创建数据库架构