Search code examples
c#entity-frameworktph

How to query objects by entity when more than 1 entity derive from a common entity and saved in the same table


Let's say I have a parent class with 2 sub-classes, with the following configuration:

modelBuilder.Entity<ParentType>(entity =>
{
   entity.HasDiscriminator()
         .HasValue<ChildA>("ChildA")
         .HasValue<ChildB>("ChildB");
}

So how do I pull the data based on the child type?

var result = context.ParentTypes.
                    .Where(x => ...);

In the table, I see a column called Discriminator with values, such as ChildA and ChildB. However, there's no such property on x.Discriminator.


Solution

  • When writing queries against a TPH (Table per Hierarchy) Entity Framework configuration, you can use the OfType<T> LinQ method to filter the types. This also lets you access the properties in that derived class. For example if we had a ChildA class like this:

    public class ChildA : ParentType
    {
        public string FavouriteFood { get; set; }
    }
    

    We could query like this:

    var childAWhoLikeCheese = context.ParentTypes
        .OfType<ChildA>()
        .Where(x => x.FavouriteFood == "Cheese");
    

    This will actually create a query something like this:

    SELECT ...
    FROM ParentTypes
    WHERE Discriminator = "ChildA"
    AND FavouriteFood = "Cheese"