Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Refactor Code/DB schema with EF 4 code first - Data Migration

What are the best practices for database refactoring with codefirst EF4?

I am interested to hear how people change the classes and the database when the RecreateDatabaseIfModelChanges option is not feasible. Migration of data will need to occur.

Currently Microsoft has a solution for doing this with model first:

http://blogs.msdn.com/b/adonet/archive/2010/02/08/entity-designer-database-generation-power-pack.aspx?PageIndex=2#comments

Does anyone have a good strategy for code first?

like image 514
Adam Gordon Bell Avatar asked Aug 29 '10 01:08

Adam Gordon Bell


People also ask

How do I code my first migration to an existing database?

Run the Add-Migration InitialCreate command in Package Manager Console. This creates a migration to create the existing schema. Comment out all code in the Up method of the newly created migration. This will allow us to 'apply' the migration to the local database without trying to recreate all the tables etc.

What are the migration commands we use with code First approach in Entity Framework?

Run Enable-Migrations command in a Package Manager console. This command added two more classes to your project in the Migrations folder. This migration was generated because Code First already created a database for us before we enabled migrations. It allows you to configure how Migrations behave for your context.

How do I update my database in migration?

After creating a migration file using the add-migration command, you have to update the database. Execute the Update-Database command to create or modify a database schema. Use the –verbose option to view the SQL statements being applied to the target database.


1 Answers

The EF team have been working on a migrations feature for EF that should solve this problem.

http://blogs.msdn.com/b/efdesign/archive/2010/10/22/code-first-database-evolution-aka-migrations.aspx

Scott Gu said on his recent tour around Europe that they should be releasing this feature soon. I'm holding my breath.

EXCITING UPDATE:

This has now been released as a CTP: http://blogs.msdn.com/b/adonet/archive/2011/07/27/code-first-migrations-august-2011-ctp-released.aspx

like image 57
Richard Garside Avatar answered Oct 18 '22 01:10

Richard Garside