Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 692
Dejan Avatar asked Feb 26 '14 10:02

Dejan


People also ask

How do I code my first migration to an existing database?

Run the Add-Migration InitialCreate command in Package Manager Console. This creates a migration to create the existing schema. Comment out all code in the Up method of the newly created migration. This will allow us to 'apply' the migration to the local database without trying to recreate all the tables etc.

How do I get rid of migrations in Entity Framework?

Delete your Migrations folder. Create a new migration and generate a SQL script for it. In your database, delete all rows from the migrations history table. Insert a single row into the migrations history, to record that the first migration has already been applied, since your tables are already there.


2 Answers

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());
    }
}
like image 68
Tobias J Avatar answered Sep 18 '22 13:09

Tobias J


Another option that worked for me in EFCore 5.0 is to use SetIsTableExcludedFromMigrations:


protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<MyEntity>().Metadata.SetIsTableExcludedFromMigrations(true);
}
like image 33
FernAndr Avatar answered Sep 19 '22 13:09

FernAndr