Entity Framework Core: Include in derive types (New in EF Core 2.1)

In the previous post we saw a way to work with inheritance in EF Core. We had the Student base class and two derived classes. These derived classes were relatively simple, what happens if in one of the derived types we have a relation to another entity? Can we make an “include” to the relationship of the derived entity? As of EF Core 2.1, the answer is yes. Let’s see an example, starting from the code of the previous entry, let’s modify the ScholarshipStudent class in the following way:

public class Scholarship
    public int Id { get; set; }
    public string ScholarshipInstitution { get; set; }
    public decimal PercentageAmount { get; set; }

public class ScholarshipStudent: Student
    public Scholarship Scholarship { get; set; }

We have created the Scholarship entity to centralize the relevant information of a scholarship. Now, ScholarshipStudent has a reference to Scholarship. After adding the migration and saving the changes in the database, we see that we can work with this new relationship. Let’s see how we can make queries to the students including the information of the scholarship:

// Queries for all students and their scholarships
var allStudents = context.Students
.Include(x => (x as ScholarshipStudent).Scholarship).ToList();

// Queries only for students with scholarships
var scholarshipStudents = context.Students.OfType()
.Include(x => x.Scholarship).ToList();

We see that in the first case we are using the as operator to cast ScholarshipStudent, and make an include to include the scholarship information in that case. In the second case, we use OfType to only querythe scholarship students, and we include the information of their scholarships.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s