How to ignore a table/class in EF 4.3 migrations

2019-01-17 13:11发布

问题:

I'm testing with EF 4.3 (beta)

I have some new classes which should generate db tables and columns.

From a old project i have some old tables in my schema, which i want to access via EF. All Classes are declared. For accessing the old table, there is a poco which is mapped.

The db migrations tries to create that old table, too.

How can it set that this class/table is not part of the migration, but part of the ef model?

xxx.OnModelCreating()    
{
    modelBuilder.Ignore<myOldTableClass>();    
}

removes the entire class from model. finally i can't use it for access via dbContext.

i like to use automatic migrations. i try to avoid to migrate old db tables completely to EF classes. (Yes, i know there are generators for that) there are 120 tables, which are still used by an old applications.

some new tables which are only used with EF (new app). there are 3 common used tables. those should not created but accessed via ef.

回答1:

With EF 4.3.1 released there is built in support for this scenario. When adding classes that are mapped to existing tables in the database, use the -IngoreChanges switch to Add-Migration.

This will generate an empty migration, with an updated meta-data signature that contains the newly added classes.

Usually this is done when starting using EF Migrations, hence the "InitialMigration" name:

Add-Migration InitialMigration –IgnoreChanges


回答2:

The correct workflow in this case is creating first migration prior to adding changes (new classes), than adding new classes and after that creating new migration where you will have only new tables.

If you didn't use migrations so far the framework will generate migrations for all tables you have in the project because it believes you are creating initial migration. Once you have migration generated you can modify its source file and remove CreateTable code for old classes from Up method. The problem is you will probably have to do this in any subsequent migration.

Edit: I wrote a walkthrough for adding migrations to existing project with EF 4.3.1