当我过滤“包含”实体时不加载相关数据

时间:2019-01-28 21:43:40

标签: c# entity-framework-6

我有以下型号

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; }
}

我根据输入的typeOfDutyId加载所有具有其角色的人:

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

但是我也需要加载RoleInDuty。我尝试以下代码:

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

但这是行不通的,VS抛出错误

  

InvalidOperationException:类型为'ct'的变量   从范围“”引用了“ System.Threading.CancellationToken”,但它   未定义

1 个答案:

答案 0 :(得分:0)

如果行为与EFCore中的行为相同, 如果仅选择实体的某些部分(因为使用匿名类型:new { ... }),则将忽略Include(&ThenInclude)。

也许您可以尝试:

var temp = _context.Persons.
  .Include(p=>p.PersonRoles)
    .ThenInclude(b=>b.RoleInDuty)
  .ToList();

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

这样可以有效地加载所有实体和依赖项,然后将其映射为匿名类型。