Code First Migrations Updates Data Structure From Code
The ADO.NET Team has announced the release of Code First Migrations Beta 1 for Entity Framework (EF). The package is available from NuGet, under the name EntityFramework.Migrations.
The Code First approach to application development means that the object model is created in code, and then the database structure is generated from that model. It's similar to Model First development, which uses the EF Designer in Visual Studio to create the data model. (For a demonstration of Code First development in action, visit the ADO.NET Team's EF 4.2 Code First Walkthrough.)
Code First Migrations is a tool that incrementally updates the existing data structure based on changes in code. This can happen automatically or manually (Microsoft is conveniently referring to these as "with-magic" and "no magic" migrations), depending on the kind of updates that are being made to the model. The types of changes that can happen automatically are:
- Adding a property or class
- Renaming a property or class (some scripting is required for this to work properly)
- Renaming a column or table without renaming its property or class
- Removing a property
In any of these instances, running the command Update-Database will automatically apply changes to the data structure.
For all other updates, Code First Migrations uses the Add-Migration command to create a script of database changes. These migrations are all saved and time-stamped, to make it possible to roll back to previous versions of the data structure. In addition to structural changes to the database, migrations can include SQL commands for manipulating data. To commit a migration, it's just a matter of running Update-Database again. In order to copy one database to another, Code First Migrations can create a SQL script using Update-Database as well:
Update-Database –TargetDatabase:"NewDatabase" –Script
Microsoft states that this beta only includes the Visual Studio implementation of Code First Migrations, but that they plan to introduce command line and MSDeploy versions as well.
Anatole Tresch Mar 03, 2015