简体   繁体   中英

Abstract class with EF Core Migrations

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?

I stumbled upon an answer, in an article on Table Per Hierarchy . In order for EF Core Migrations to be able to work with abstract classes, you must manually define the discriminator. So I needed the following in the OnModelCreation() in the DbContext file:

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<Base>()
        .ToTable("Base")
        .HasDiscriminator<string>("BaseType")
        .HasValue<A>("A")
        .HasValue<B>("B");
}

Of course you can configure the discriminator however you like, but it must be explicitely configured.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM