-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Description
Originally filed as #2725 (comment) by VeMike
So how would I ignore just a base class, but not a derived class using this approach?
Consider the following model:
[Table(nameof(Human))]
public class Human
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int HumanId { get; set; }
public int Age { get; set; }
}
[Table(nameof(Developer))]
public class Developer : Human
{
public string MainLanguage { get; set; }
}
The database context for this model is the following
public class FooContext : DbContext
{
public DbSet<Developer> Developers { get; set; } = null!;
/// <inheritdoc />
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// This is made to get TPT
modelBuilder.Entity<Human>().ToTable(nameof(Human));
modelBuilder.Entity<Developer>().ToTable(nameof(Developer));
modelBuilder.Entity<Human>().ToTable(nameof(Human), t => t.ExcludeFromMigrations());
}
/// <inheritdoc />
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
base.OnConfiguring(optionsBuilder);
optionsBuilder.UseSqlServer("<FooBarConnectionString>");
}
}
As you can see I only want Developer
to be in the migration. Human
should be excluded. Why would I want to do this? I am extending an existing model and the base (Human
) already exists in the database. I want to add Developer
to this existing model.
But if I create a migration the whole hierarchy of Human
is excluded (basically all classes of type Human
). But I want the Developer
to be created.
Of course, I could just remove the line
modelBuilder.Entity<Human>().ToTable(nameof(Human), t => t.ExcludeFromMigrations());
and then manually remove the added Human
from the migration. But is there a way to do this automatically?