IT:AD:EF/CodeFirst/Migrations:HowTo:Add-Migration
Summary
So…if Enabling Migrations and using IT:AD:EF/CodeFirst/Migrations:HowTo:Update-Database is too easy/dangerous, what's the safer approach?
Process
The solution MS is pushing is to be more … careful.
- Make changes to an Entity
- Try to run
- Get the exception that says the Model has changes
- This time, instead of invoking IT:AD:EF/CodeFirst/Migrations:HowTo:Update-Database (with AutomaticMigrations=true), invoke:
Add-Migration {MyUniqueName} -startupprojectname:App.AppHost.Web -projectname:App.Infrastructure -verbose -debug
This creates a new file in the Migrations folder, outlining the shape of the same entity, but with the added property.
Using a coded Migration file is referred to by MS as a Coded Migration.
Note:
- File name has date prefix to provide processing order
- Class that enherits from
DbMigration
Note:
Given the limitations of automatic migrations we recommend using code-based migrations in team environments.
Src: MS: http://msdn.microsoft.com/en-US/data/jj554735
Example Code Migration
namespace XAct.Spikes.CodeMigration.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class AddEstimateDescription : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.Estimates",
c => new
{
Id = c.Int(nullable: false, identity: true),
Name = c.String(nullable: false, maxLength: 50),
Amount = c.Double(nullable: false),
Description = c.String(),
})
.PrimaryKey(t => t.Id);
}
public override void Down()
{
DropTable("dbo.Estimates");
}
}
}
Commands
Examples of the commands you have at your disposal to craft Migrations are:
- AddColumn(“dbo.Blogs”, “Url”, c ⇒ c.String());
- DropColumn(“dbo.Blogs”, “Url”);
- AddTable
- DropTable
See more examples here:
Update-Database
Now that the Migration is created, we can now update the Db using IT:AD:EF/CodeFirst/Migrations:HowTo:Update-Database.