EF Core TPC Inheritance strategy - Select query to include individual navigational property
Hello,
I have 2 similar entities, which are derived from a base class. The base class is
Animal, while Cat and Dog are concrete types. Two tables are created for the concrete types. In addition Dog also has a navigational property, called Owner.
If a DbSet<Animal> Animals is defined, then both tables can be queried at the same time, by running _dbContext.Animals.ToList() (this will do a UNION ALL in the background).
The problem is that this way the navigational property Owner for Dog type is not included, since _dbContext.Animals does not have Owner property. I could make it work the following way:
This works, but I don't think this is the right way to do it, since Cat is part of the queried entities too, and I also get a warning Dereference of a possibly null reference. I think it will try to map each type to Dog and a Cat mapped to Dog will be null. How could I specify to include the navigational property related to Dog entities?2 Replies
This seems to match EF Core's own documentation on including values from derived types, not sure if there's anything you need to change.
https://learn.microsoft.com/en-us/ef/core/querying/related-data/eager#include-on-derived-types
Eager Loading of Related Data - EF Core
Eager loading of related data with Entity Framework Core
Thanks! The article was helpful, with explicit conversion the warning goes away