6
votes

So I have a basic problem trying to generate a migration when I don't have a DB in sync (up to the latest migration, in fact, have no DB at all) and have already made substantial changes to my model.

This are the specific details:

  1. Have a sequence of explicit migrations.
  2. Have no database. In short, have lots of pending changes.
  3. Made changes to the models/context.
  4. When trying to Add-Migration, it will complain saying precisely that explicit migrations are pending.
  5. If I try to execute the migration (and bring my DB in sync), either via Update-Database or migrate.exe, it will fail (after applying explicit migrations successfully), and automatic migrations are not enabled.
  6. I don't want to enable automatic migrations either (to prevent any schema changes to be committed and go unaccounted in code.)

I realize that after the failure in #5 I can now run #4. Then re-try #5 and voilá.

My Question is if this is the expected approach to solve this silly situation.

2
If you have no DB currently, you can just delete the migrations folder and call dbCtx.Database.Delete() to start the whole thing fresh from your models. - SimpleVar
How did you get multiple migrations without a database? - Dismissile
@Dismissile: We are a team of N devs and some of us have local DBs that are behind latest migrations, As I described above, the dev gets latest code and starts to make model changes without having run pending migrations; that's a typical scenario. Another one is if the dev has never even worked on the project and now gets all the code for the first time. - Fernando Espinosa
@YoryeNathan: I'm afraid that is not a feasible approach — this is not a personal project: it's a team project AND it's already been releases to several environments at different versions. - Fernando Espinosa

2 Answers

13
votes

I would use the following approach.

First you need to apply migrations and specify the last one.

PM> Update-Database -TargetMigration AnyMigrationName

# It updates database to a migration named "AnyMigrationName"
# This will apply migrations if the target hasn't been applied or roll back migrations
# if it has

When your local database is updated you simply add new migration.

PM> Add-Migration NewMigrationName

# it scaffolds a new migration named "NewMigrationName" 

Looking for a good reference I found these blog posts about EF Migrations that can help you a lot. They cover many questions and EF Migrations and a Merge Conflict and EF Migrations Command Reference in particular.

1
votes

this error is shown when you have many Migrations pending.

If you don't need existing migrations, first delete (exclude) all migration on Migration folder and then add a new migration.

Add-Migration new