Entity Framework Core: Include on TPH

c# entity-framework entity-framework-core

Question

We have the following model in EFCore set up using Table Per Hierarchy (simplified for clarity):

public class User {
  public int Id { get; set; }
}
public class Student : User {
  public Company Company { get; set; }
}
public class Teacher : User {
  public Company School { get; set; }
}

I want to get all users (both Students and Teachers) with all references included. Basically I want to do the following in one query:

_context.Users.OfType<Teacher>().Include(x => x.School);
_context.Users.OfType<Student>().Include(x => x.Company);

Is there a way to do that?

1
0
2/17/2018 11:53:23 AM

Accepted Answer

From Ivan's comment, current (pre EFCore 2.1) solution is:

var users = _context.Users.Where(_filter_conditions_here).Skip().Take(_if_you_like_);
var userIds = users.Select(x => x.Id).ToList()
_context.Users.OfType<Teacher>().Where(x => userIds.Contain(x.Id)).Include(x => x.School).ToList();
_context.Users.OfType<Student>().Where(x => userIds.Contain(x.Id)).Include(x => x.Company).ToList();
0
2/17/2018 1:16:36 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