Thursday, January 7, 2021

EF Core 5.0: Excluding Tables from Migrations

In this post, let's see how we can exclude Tables from Migrations in EF Core 5.0. It's actually pretty easy.

Consider the below use case.

public class IdentityDbContext : DbContext
{
    public DbSet<ApplicationUser> ApplicationUsers { getset; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // Configuring
    }
}

public class OrderDbContext : DbContext
{
    public DbSet<ApplicationUser> ApplicationUsers { getset; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // Configuring
    }
}

public class ApplicationUser
{
    public int Id { getset; }

    public string Name { getset; }
}

Here the ApplicationUser is shared between two DbContexts (IdentityDbContext and OrderDbContext). And now let's say between these two DbContexts, we are only going to maintain full ApplicationUser information in only IdentityDbContext. In that case, we don't want further changes on ApplicationUser to be applied on OrderDbContext.

To achieve that, we can exclude the ApplicationUser in migrations for OrderDbContext as below.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<ApplicationUser>().ToTable("ApplicationUsers", t => t.ExcludeFromMigrations());
}

Unfortunately, we need to call ToTable and from there customize the TableBuilder to ExcludeFromMigrations.

Hope this helps.

Happy Coding.

Regards,
Jaliya

1 comment: