Entity Framework - TPH Inheritance with Null Database Fields

619 views Asked by At

I have 2 subclasses inheriting from the same base class. They all map back to the same table. If field1 in the db table is null and field2 is not null, it's one subclass. If field1 is not null and field 2 is null, it's the other subclass.

I keep getting an error. The actual message is: "Invalid column name 'Discriminator'." It actually says Discriminator... I didn't throw that in as a generic term.

Here is a sample of my code:

DatabaseTableA
TableAId ( PK , int )
FooId ( FK , int , null )
BarId ( FK , int , null )
Prop1 ( int )
Prop2 ( int )
Prop3 ( int )


public abstract class BaseClass
{
    public int Prop1{ get; set; }
    public int Prop2{ get; set; }
    public int Prop3{ get; set; }
}

public class Foo : BaseClass
{
    public int FooId{get;set;}
}

public class Bar : BaseClass
{
    public int BarId{get;set;}
}

internal class BaseClassMap : EntityTypeConfiguration<BaseClass>
{
    public BaseClassMap()
    {
        ToTable("DatabaseTableA");
        HasKey( e => e.TableAId);

        Map<Foo>( m => m.Requires("BarId").IsDBNull());
        Map<Bar>( m => m.Requires("FooId").IsDBNull());
    }
}

How do I map this correctly?

1

There are 1 answers

1
toddmo On

Entity Framework will assume that any class that inherits from a POCO class that is mapped to a table on the database requires a Discriminator column, even if the derived class will not be saved to the DB.

See the solution here EF Code First "Invalid column name 'Discriminator'" but no inheritance