Don't work Loading Related Data when i filter "Include" entities

c# entity-framework-6

Question

I have the following models

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

I load all people with their roles according entered typeOfDutyId:

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

But i need load RoleInDuty too. I try the following code:

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();

But it is does not work, VS throw error

InvalidOperationException: variable 'ct' of type 'System.Threading.CancellationToken' referenced from scope '', but it is not defined

1
0
1/28/2019 9:43:40 PM

Accepted Answer

If the behaviour is the same as in EFCore, Include (& ThenInclude) are ignored if you select only some part of the entity (because you use an anonymous type : new { ... }).

Maybe you can try :

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()

This has for effect to load all the entity & dependencies, and then map it to an anonymous type.

0
1/28/2019 10:06:28 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow