Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF TPH Inheritance Query

Trying to implement a very simple TPH setup for a system I'm making, 1 base, 2 inherited classes.

However the inherited classes all belong to the same entity set, so within my ObjectContext using loop, I can only access the base abstract class. I'm not quite sure how I get the elements which are concrete classes? (I've also converted it to using POCO).

alt text

Then within my application using the Entities:

using (SolEntities sec = new SolEntities()) {
    Planets = sec.CelestialBodies;
}

There's a CelestialBodies entity set on sec, but no Planets/Satellites as I'd expect.

Not quite sure what needs to be done to access them.

Thanks

like image 653
Psytronic Avatar asked Jan 02 '11 13:01

Psytronic


People also ask

What is TPH inheritance?

TPH inheritance uses one database table to maintain data for all of the entity types in an inheritance hierarchy. In this walkthrough we will map the Person table to three entity types: Person (the base type), Student (derives from Person), and Instructor (derives from Person).

How does EF support inheritance?

By default, EF maps the inheritance using the table-per-hierarchy (TPH) pattern. TPH uses a single table to store the data for all types in the hierarchy, and a discriminator column is used to identify which type each row represents.

Does EF core cache query results?

The results of EF commands will be stored in the cache, so that the same EF commands will retrieve their data from the cache rather than executing them against the database again. So this library returns cached results if the generated SQL is the same.


2 Answers

You can use the OfType method:

using (SolEntities sec = new SolEntities()) {
    Planets = sec.CelestialBodies.OfType<Planet>();
}
like image 103
Thomas Levesque Avatar answered Sep 19 '22 17:09

Thomas Levesque


As Thomas Levesque described OfType extension method will allow you querying only single inherited type you really want to access. If you access CelestialBodies directly you will get all entities. Every entity will be of type Planet or Satellite but you will have to cast them to access their properties.

like image 35
Ladislav Mrnka Avatar answered Sep 21 '22 17:09

Ladislav Mrnka