captainjamie captainjamie - 1 year ago 87
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))

But how can I do:

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

Without turning lazyloading on?

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download