Reputation: 491
In short, what I am trying to do, is add the power of migrations into a project that is mature and changes always been handled manually using sql.
I have been assigned a project that uses Entity Framework, but all database-changes were done manually without using migrations.
Earlier when new changes were introduced we would create the models in code, update the context with new tables, then use Entity Framework PowerTools to generate the sql and then update the database manually.
So today we have a complete database, we have a databasecontext, as well as carefully crafted EntityTypeConfiguration classes. So this is a code-first situation, but the database already exists.
The challenge is that after I run
'Enable-Migrations'
'Add-Migration'
I am stuck with a complete Up() function that tried to create the entire database if I do
'Update-Database'.
What I think I want to do is set a flag in the database that the current state is the status-quo, and that my current Up() function only will be used when creating a brand new database.
After that I want all changes to the database be handled by EF-migrations.
Is this possible? and how?
Thanks in advance
Upvotes: 0
Views: 238
Reputation: 1916
OPTION 1: Create migration that starts from the current model
You can use the –IgnoreChanges
parameter with Add-Migration
command:
Add-Migration MigrationName –IgnoreChanges
This creates an empty migration with the current model as a snapshot.
OPTION 2: Create full migrations that create database from scratch, but skip the first migration on some databases
Entity Framework uses __MigrationHistory
table to keep track of migrations that have already been executed. When the first migration is executed on the database, it gets inserted in __MigrationHistory
table. Next time Update-Database
command is called, EF looks at __MigrationHistory
table and skips the migrations that are already applied to the database.
To make a specific database skip the first migration, you can do the following:
Enable-Migrations
Add-Migration InitialCreate
Update-Database -Script
CREATE TABLE [__MigrationHistory]
INSERT INTO [__MigrationHistory] ...
and execute these statements on the database.
Now this database has the information that the InitialCreate
migration has already been applied, and any further calls to Update-Database
against this specific database will skip the InitialCreate
migration.
Upvotes: 3