3

This question answers how to eager load the property of a derived class using include: Eager loading property of derived class using Include

This question answers how to load derived entity and object property of derived entity from a parent entity, but I believe it relies on lazy loading (please correct me if I'm wrong): Entity Framework - Eager loading of subclass related objects

My situation is similar to these, but I want to eager load properties on the derived entities from a parent entity when I have lazy loading explicitly disabled. Here is an example in the context of the other post:

Person
{
   Name
   Address
}

Employee : Person
{
   Compensation - object
}

Visitor : Person
{

}

Company
{
    ICollection<Person> People
}

In this example, I would want an expression to eager load Compensation objects when querying from the Company collection. My initial thought is to do something like this:

public IQueryable<Company> CompanyWithPeople() {
  return Context.Company
    .Include(c => c.People)
    .Include(c => c.People.OfType<Employee>().Select(e => e.Compensation));
}

But that gives an error:

System.ArgumentException : The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.

Is there any way to eager load the derived entity AND object properties of the derived class from a parent entity?

Community
  • 1
  • 1
  • I dont know if this will work, but Have you tried adding a navigation property `ICollection Employees { get; set; }` to the `Company` class? – Sam I am says Reinstate Monica Aug 25 '16 at 21:42
  • I believe that would work, but in my specific situation I have potentially dozens of entities that derive from Person, so I don't really want to add an extra navigation property to Company every time I add a derived class. I may use that as a temporarily solution though. – jondavidford Aug 26 '16 at 12:06
  • Actually, it looks like that won't work without changing my database structure drastically (and unnecessarily). When I add ICollection Employees to the Company class, entity framework thinks that it is another relation and thinks that their will be another table to represent the many to many relationship between Employees and Company, whereas it is actually already represented in the many to many table for Company to Person. Right now I'm just going to have to use two separate loads (one for Company, one for person) and then combine them together. – jondavidford Aug 26 '16 at 14:52
  • 1
    you mean bypass the ORM entirely and just write my own query and mapping code? – jondavidford Aug 26 '16 at 15:41
  • Nevermind what I just said. I forgot this question was about eager loading and `.Include` – Sam I am says Reinstate Monica Aug 26 '16 at 15:52

0 Answers0