How to create Table per type inheritance in Entity Framework Core 2.0 code first?

.net-core entity-framework entity-framework-core

Question

Following code generates only single table "CertificateEvent".

How do I achieve TPT inheritance in EF Core 2.0?

public abstract class CertificateEvent {
   public int CertificateEventId { get; set; }
}

public class Assignment : CertificateEvent {...}
public class Assessment : CertificateEvent {...}

public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
    {

    }

    public DbSet<Assessment> AssessorAssessments { get; set; }
    public DbSet<Assignment> AssessorAssignments { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<CertificateEvent>().ToTable(nameof(CertificateEvent));
        modelBuilder.Entity<Assessment>().ToTable(nameof(Assessment));
        modelBuilder.Entity<Assignment>().ToTable(nameof(Assignment));
    }
}

class MyDesignTimeDbContextFactory : IDesignTimeDbContextFactory<MyDbContext>
{
    public MyDbContext CreateDbContext(string[] args)
    {
        var builder = new DbContextOptionsBuilder<MyDbContext>();
        builder.UseSqlServer("Server=(local);Database=Test;Trusted_Connection=True;MultipleActiveResultSets=true");
        return new MyDbContext(builder.Options);
    }
}

I've also tried dotnet ef migrations add Inheritance, but it did not created TPT inheritance in the database

1
2
9/12/2017 3:07:42 PM

Popular Answer

TPT is not in EF Core (yet). See

The feeling from our team is that TPT is generally an anti-pattern and results in significant performance issues later on. While enabling it may make some folks "happier" to start with it ultimately just leads to issues. We are willing to consider it though, so we're leaving this open and will consider it based on the feedback we get.

https://github.com/aspnet/EntityFrameworkCore/issues/2266

2
9/12/2017 3:41:43 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow