Entity Framework TPC inheritance problem

advertisements

I'd like to have Table Per Concrete type inheritance in my application:

public class Row {
    public int Id {get;set;}
    public string Name {get;set;}
}

public class ExtendedRow : Row {
    public int Weight {get;set;}
}

Each of the classes need to be mapped to their own view and ExtendedRow view has all the columns of Row view.

My configuration is:

    modelBuilder.Entity<Row>().Map(m => {
        m.MapInheritedProperties();
        m.ToTable("Row");
    });
    modelBuilder.Entity<ExtendedRow >().Map(m => {
        m.MapInheritedProperties();
        m.ToTable("ExtendedRow");
    });

Querying ExtendedRow is just fine. However, querying Row generates the following SQL:

SELECT
        [Extent1].[Id] AS [Id],
        [Extent1].[Name] AS [Name]
        FROM [dbo].[Row] AS [Extent1]
UNION ALL
SELECT
        [Extent2].[Id] AS [Id],
        [Extent2].[Name] AS [Name]
        FROM [dbo].[ExtendedRow] AS [Extent2]

Why does EF add UNION ALL operator? How do I fix it?


There are several issues on stack overflow about this topic.
EF works in the way you see, if you ask for Base you will receive all objects that implements Base (i.e. Base and derived objects). If you use TPC you will see UNION, if you use TPH you will see that EF omits the where clause on the discriminator field (i.e. it does not matter TPC or TPH, the result is always the same). GetType is not an EF canonical function so you can't use it but I've read that with EF 6.x you can use is (in your case !(m is ExtendedRow)). Actually I don't know if it works.

Usually I don't map Base class (i.e. I make an empty class that derive from base than I map it).