Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework code based migrations, how is order determined?

I'm using EF 5.0 and I would like to start using Code-based migrations

I've used fluent migrator and there is a concept of migration order. Migrations can be migrated/rollback no matter the database's migration version.

Does Entity Framework have similar functionality?

I was planning on keeping multiple migration implementations for each database version (likely tied to sprint number at first).

Why do i want this?

Our continuous integration will migrate the database for each environment. It's likely that our Dev build will only be one version "behind" but when we go to QA or PROD environment the database will be behind by multiple migrations.

Maybe i'm going about this the wrong way, in which case I would love to hear opinions on the best way to do migration with CI.

like image 745
mswanson Avatar asked Mar 06 '13 16:03

mswanson


People also ask

What is code based migration?

Code-based migration is useful when you want more control on the migration. When you add, remove, or change entity classes or change your DbContext class, the next time you run the application it automatically deletes your existing database, creates a new one that matches the model, and seeds it with test data.

How does EF migration work?

EF Core compares the current model against a snapshot of the old model to determine the differences, and generates migration source files; the files can be tracked in your project's source control like any other source file. Once a new migration has been generated, it can be applied to a database in various ways.

How do you use migration in code first approach?

Go to Package Manager Console and type command help migration. Type Enable-Migrations -ContextTypeName EXPShopContext. This command creates a migration folder with InitialCreate.


1 Answers

Yes EF has this functionality.

When you run Add-Migration you'll notice the migration file is prefixed with a timestamp. This is what determines the order, assuming automatic migrations are and always have been disabled.

If you are using a mixture of explicit migrations and automatic migrations then you may notice an additional Source property in the .resx file generated with your migration. This is how EF will determine if it needs to run an automatic migration before it runs your explicit migration.

My experience has taught me these guidelines:

1) Never use automatic migrations.

2) Every developer on your team should ensure they have the latest code before creating a new explicit migration. Sort of obvious, but creating migrations from stale code will result in problems.

3) Developers should make sure that if they write custom SQL in the Up() method of the migration then they write appropriate code (and test it!) to reverse those changes in the Down() method.

like image 198
Dave Graves Avatar answered Oct 05 '22 17:10

Dave Graves