3.08.2013

EF Code First Migrations - How To Sync To Production DB

It's very simple to push out the changes in the database across any db that would need the changes, be it your test, staging or production servers. All you have to do is to create a SQL script via Update-Database with a -Script flag:
PM>Update-Database -Script -SourceMigration: $InitialDatabase -TargetMigration: AddPostAbstract
Because of the -Script switch, Code First Migrations will run the migration pipeline but instead of actually applying the changes it will write them out to a .sql file for you. Neat.

Complete write up from Microsoft is here.

If you are doing this for the first time, and you need all the changes so far, you just need to do this:
PM>Update-Database -Script -SourceMigration: $InitialDatabase
Here's a sample PM console session:
PM> Update-Database -Script -SourceMigration: $InitialDatabase
Applying code-based migrations: [201301240307501_Initial, 201302020143144_ModifiedEmailTableAndAddedSignatureTable, 201302020149599_AddedCreatorToSignatureRelation, 201302020158207_ChangeSignatureIdToNullable, 201302050122407_AddResultingImageFileToSignatureTable, 201302050154113_AddLabelToSignatureTable, 201302052134222_ChangedAddressToHave3LineItems, 201302090226121_ChangedSignatureFileToRequired, 201302121909589_AddedSalesItemClass, 201302192149411_AddedCustomerClass, 201302210141465_AddedLocationInIamProfileClass, 201302260305398_UpdatedCertificateClass].
Applying code-based migration: 201301240307501_Initial.
Applying code-based migration: 201302020143144_ModifiedEmailTableAndAddedSignatureTable.
Applying code-based migration: 201302020149599_AddedCreatorToSignatureRelation.
Applying code-based migration: 201302020158207_ChangeSignatureIdToNullable.
Applying code-based migration: 201302050122407_AddResultingImageFileToSignatureTable.
Applying code-based migration: 201302050154113_AddLabelToSignatureTable.
Applying code-based migration: 201302052134222_ChangedAddressToHave3LineItems.
Applying code-based migration: 201302090226121_ChangedSignatureFileToRequired.
Applying code-based migration: 201302121909589_AddedSalesItemClass.
Applying code-based migration: 201302192149411_AddedCustomerClass.
Applying code-based migration: 201302210141465_AddedLocationInIamProfileClass.
Applying code-based migration: 201302260305398_UpdatedCertificateClass.
Once the script is generated, Visual Studio opens the script for you to save. What I do is just simply copy and paste the resulting sql script to SQL Server Management Studio, then execute it there against the database. Done!

There's a little hickup:
I got this error message, which means that the script generator is unable to remove duplicate variable declarations in the sql. The solution is to simply delete such duplicate declarations.

Msg 134, Level 15, State 1, Line 101 The variable name '@var0' has already been declared. Variable names must be unique within a query batch or stored procedure.

No comments:

Post a Comment