Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eager loading property of derived class using Include

I have classes like:

Person
{
   Name
   Address
}

Employee : Person
{
   Compensation - object
}

Visitor : Person
{

}

If I write linq:

var persons = Context.Persons
                .Include("Compensation");

I get error:

A specified Include path is not valid. The EntityType 'Person' does not declare a navigation property with the name 'Compensation'.

It works ok if I do:

var persons = Context.Persons
                .OfType<Employee>()
                .Include("Compensation");

But I would like to get Employees and visitors in the same query.

Looks like there is a request for this feature on EF4 UserVoice: http://data.uservoice.com/forums/72025-ado-net-entity-framework-ef-feature-suggestions/suggestions/1249289-include-property-of-derived-classes?ref=title

but it does not look like it will get done any time soon.

What is a good workaround for this issue?

like image 490
Eric P Avatar asked Jun 07 '11 09:06

Eric P


2 Answers

You can try it this way:

var persons = Context.Persons
                     .OfType<Employee>()
                     .Include("Compensation")
                     .Concat<Person>(Context.Persons.OfType<Visitor>());
like image 132
Ladislav Mrnka Avatar answered Oct 23 '22 04:10

Ladislav Mrnka


Here's a nice example of how to load Persons and include Compensation for Employees

Replace Reference() by Collection() for a collection property.

IQueryable<Person> GetPersons()
{
    var persons = Context.Persons;
    foreach(var entry in persons.OfType<Employee>())
        Context.Entry(entry).Reference(e => e.Compensation).Load();
    return persons;
}

Not sure either if it's efficient, but it works, and the intention is clearer than with joins.

Based on this SO answer

like image 32
Jerther Avatar answered Oct 23 '22 04:10

Jerther