In previous posts I created a database using EF code-first and I enabled migrations.
Now lets try some advanced topics:
- Downgrades & migrations to specific versions
- Customizing Migrations
- Execute custom SQL with the migration
- Get migration generated SQL
- Auto migrate when the application start and additional actions
Downgrades & migrations to specific versions
To migrate to an specific version run in command in Package Manager Console.
Update-Database –TargetMigration: MigrationName
Customizing Migrations
Let’s add a couple of new properties to our Model and add a migration to generate the default migration. We will add some information to our recipes:
- A name: the name shall be unique for each recipe.
- A complexity index: each recipe shall have a complexity index from 1 to 3, the default complexity level shall be 2.
This is our new Recipe class with a name and complexity index:
public class Recipe { // Primary Key public int RecipeId { get; set; } // EF needs the virtual attribute to enable Lazy loading public virtual List<Food> Ingredients { get; set; } // Recipe description public string Description { get; set; } // Recipe name [Index(IsUnique = true)] [MaxLength(200)] public string Name { get; set; } // Recipe complexity [Range(1, 3)] [DefaultValue(2)] public int Complexity { get; set; } }
Add the default migration:
PM> Add-Migration Recipe_NameAndComplexity
Scaffolding migration ‘Recipe_NameAndComplexity’.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running ‘Add-Migration Recipe_NameAndComplexity’ again.