I am trying to find how to include navigation properties of dervied type.
The example:
public abstract class BaseType
{
public int Key {get;}
{
public class FirstChild : BaseType
{
public Link Link { get; }
}
public class Link
{
}
I would like to get all instances of BaseType using one query. I can do simply:
DbContext.BaseTypes.ToList()
However I would like to get all instances plus include FirstChild.Link
I cannot do
DbContext.BaseTypes.Include(x => x.Link).ToList()
What I found on SO is to use two separate queries. Is it achivable from one query ( using casting ? ).
This is shown in the docs, in Include on derived types in the Eager Loading docs. If you have Person and Student types like these:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Student : Person
{
public School School { get; set; }
}
public class School
{
public int Id { get; set; }
public string Name { get; set; }
public List<Student> Students { get; set; }
}
You can include student schools by casting in the Include
call :
context.People.Include(person => ((Student)person).School).ToList()
Or you can specify the navigation property by name :
context.People.Include("School").ToList()