captainjamie captainjamie - 1 month ago 10
C# Question

How to include a collection from a derived object in entity framework

Sorry, that title wasn't great. Say I have some classes:

public abstract class Person {
public int ID { get; set; }
}

public class Student : Person {
public Student() {
Grades = new List<Grades>();
}
public virtual ICollection<Grades> Grades { get; set; }
}

public class Teacher : Person {
public string Class { get; set; }
}
public class Grades {
public int Score { get; set; }
}


This is all mapped up correctly using Entity Framework and I can do:

using (var db = new DataContext()) {
foreach (var student in db.People.where(p => p is Student))
Console.WriteLine(student.ID);
}


But how can I do:

db.People.where(p => p is Student).Include(s => s.Grades)


Without turning lazyloading on?

Answer

You can use the OfType to filter by type and then apply an Include on it.

var students = db.People.OfType<Student>().Include(s => s.Grades);