Hello i am trying to use derived classes using EF Core using a single concrete table containing the reunion of the derived types.
public abstract A
{
public int Id{get;set;}
}
public B:A
{
public string Name{get;set;}
}
public C:A
{
public bool IsMan{get;set;}
}
public class MyContext:DBContext
{
public DBSet<A> ATable {get;set;}
}
When the database gets generated the Table ATable
does not contain the fields of the C
subtype.The resulting table contains only A
-s fields and B
-s.
Generated table
Id
Name
P.S Do i need to use some kind of discriminator ? I just want one table that has the reunion of the two subtypes , and to be able to access it using OfType
Linq
extension.
What you are describing is called TPH (Table per Hierarchy) inheritance strategy and currently is the only supported pattern by EF Core.
However, unlike EF6 EF Core does not automatically detect the derived entities by reflecting the model assembly. This was causing unexpected side effects in EF6, hence has been removed and now you are required to explicitly include derived types in the model (if not included by other mechanisms like navigation properties or explicit DbSet
s). This is explained in Entity type hierarchy mapping section of EF Core documentation:
By convention, EF will not automatically scan for base or derived types; this means that if you want a CLR type in your hierarchy to be mapped, you must explicitly specify that type on your model. For example, specifying only the base type of a hierarchy will not cause EF Core to implicitly include all of its sub-types.
So, the minimum you need to get TPH with your sample model is either adding
public DbSet<B> Bs { get; set; }
public DbSet<C> Cs { get; set; }
or Entity
fluent API:
modelBuilder.Entity<B>();
modelBuilder.Entity<C>();