tomwaitforitmy
tomwaitforitmy

Reputation: 727

How to make EF Migrations work empty AND existing database as starting point?

According to Microsoft documentation you have two options to add an initial Migration for code-based Migrations in EF:

  1. Use an exinsting Database (Add-Migration InitialCreate –IgnoreChanges). You should use this approach when other databases that migrations will be applied to in the future will have the same schema as your local database currently has.

  2. Use an empty Database (Add-Migration InitialCreate). You should use this approach when other databases that migrations will be applied to in the future are empty (or do not exist yet).

We are trying to switch form automatic migrations to code-based migrations and we need to make both options happen, because (1.) we have an application already installed and running at a customer place and (2.) we want to install more applications fresh.

How can we achieve this?

I have two ideas how to realize this, but no clue about side effects or trouble I might run into.

Side note: We used the existing database approach (1.) to migration the installed application successfully, as exampled in another post. Obviously, fresh installations don't work like that.

Upvotes: 0

Views: 1370

Answers (1)

Colin
Colin

Reputation: 22595

If you have already used the existing database approach to migrate the installed application successfully then that database will have an entry in the __MigrationHistory table with a migrationid that matches the filename of the initial migration, and any code that you now place in the Up method will not run. Unfortunately you can't force a re-scaffold of the initial migration for new applications, so here is what I would do:

  1. Delete the entry in the __Migrations table
  2. Delete your Initial migration
  3. Add-Migration InitialCreate to scaffold the code required to create your database
  4. Comment out the code in the Up method, or just add a return at the top to prevent it executing.
  5. Apply the migration to your existing database.
  6. Uncomment the code in the Up method so that it executes for future new application

Upvotes: 1

Related Questions