0

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?

3
  • In reality the query involves pagination (I want to display first 10 users sorted by Id, regardless whether they are teachers or students)
    – Shaddix
    Feb 17, 2018 at 11:54
  • 1
    You need to wait for EF Core 2.1 - Include for derived types item
    – Ivan Stoev
    Feb 17, 2018 at 12:18
  • thanks, that actually answers my question :)
    – Shaddix
    Feb 17, 2018 at 13:11

1 Answer 1

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.