Search code examples
entity-framework

How to exclude one table from automatic code first migrations in the Entity Framework?


I'm using the Entity Framework in the Code First mode with automatic migrations enabled. Now, I have one entity whose table should not be managed (migrated) by the EF. Is there a way of disabling automatic migrations for one specific entity (i.e. table)?


Solution

  • This is now possible in EF Core 5.0 using the ExcludeFromMigrations() method, but strangely enough you have to call the ToTable() method and then use the TableBuilder.

    https://devblogs.microsoft.com/dotnet/announcing-entity-framework-core-efcore-5-0-rc1/#exclude-tables-from-migrations

    public class ReportingContext : DbContext
    {
        public DbSet<User> Users { get; set; }
    
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>().ToTable(nameof(Users), t => t.ExcludeFromMigrations());
        }
    }