I have couple of classes which inherits 1 base abstract class. It is mapped via fluent API to existing database (using Table-Per-Concrete-Type, i.e. base abstract class not mapped to any table).
Now I want to add some statistics to my code and the best solution for me is to use TPH approach for 3-4 new classes. It maybe or maybe not inherits the same class as described above.
But I do not know how to instruct EF use TPH-approach for these 3-4 classes. Am I need to add correect table with discriminators and it will be used ok? Or I need to specify it somehow via fluent API?
I found. You do not need to specify somehow EF that you want to use TPH. Enough to do following:
Create classes hierarchy
class Base { ... }
class Derived1 : Base { ... }
class Derived2 : Base { ... }
.......
class DerivedN : Base { ... }
Create table called as your base type (otherwise do not forget to map it using ModelBuilder) with common columns (content of Base
) and with one column per public property in each derived types. Add "Discriminator" column (nvarchar(128)
, but I suggest to use varchar unless you using unicode classes names).
In your successor of DbContext add only one DbSet: DbSet<Base> Data { get; set; }
and use it for CRUD operations.
That is all!