I have previously been succesful in using an abstract base class in a DbSet
and then inherit multiple classes from it. This would mean that all inherited classes mapped to the same table, only using the columns they needed. More details can be found in this post (also asked by me), but in short, it looked a bit like this:
public abstract class Base
{
public int Id { get; set; }
public DateTime CreatedDtm { get; set; }
}
public class A : Base
{
public string PhoneNo { get; set; }
}
public class B : Base
{
public string EmailAddress { get; set; }
}
public DbSet<Base> Bases { get; set; }
The table used for both this classes would then have the following columns:
- Discriminator - Added by EF to track what type of class it is (A or B)
- Id (used by both classes)
- CreatedDtm (used by both classes)
- PhoneNo (only used by A, so always null for B)
- EmailAddress (opposite of PhoneNo)
It works when I create the table myself. But when I try to create it via EF Core Migrations, I get the following error:
The corresponding CLR type for entity type 'Base' is not instantiable and there is no derived entity type in the model that corresponds to a concrete CLR type.
Other posts (like this) suggest that what I am trying to do is not possible, and that I need to use Table-per-Type mapping. But I have seen it work, so it cannot be in all cases. Is it possible (without bending the universe) to use an abstract base class and a single table, with EF Core Migrations?