Entity Framework 6 NuGet Cheat Sheet

By SharkBoy SharkBoy

The following is a cheat sheet that shows the available command that can be run in the Visual Studio NuGet console to create and run database migrations when using the Entity Framework 5 code first model.

Enabling Migrations for you project

Before running this command you need to have installed the Entity Framework NuGet package and have at least one class defined in your project that is derived from the DbContext class.

Sample 1 – Scaffold a migration configuration class with default settings

Enable-Migrations

Sample 2 – Specify a context class

Enable-Migrations –ContextTypeName “NameOfContextClass”

Sample 3 – Enable Automatic Migrations

Enable-Migrations –EnableAutomaticMigrations

Sample 4 – Enable Migrations on a specific context class for specific project

Enable-Migrations –ContextTypeName “NameOfContextClass” –ProjectName “YourProjectName”

Sample 5 – Specify a connection string name

Enable-Migrations –ConnectionString “NameOfAConnectionStringDefinedInWebConfig”

Sample 6 – Force overwrite existing migration configuration class

Enable-Migrations -Force

Adding migrations to your project

Before running this command you need to have installed the Entity Framework NuGet package and have at least one class defined in your project that is derived from the DbContext class. You also must have created a migration configuration class using the Enable-Migration command.

First Migration in project

Add-Migration -Name "first"

Remove Last Migration in project

If you would like to roll back the last migration you added you can use the following command:

Remove-Migration

Appling migrations to your database

Before running this command you need to have installed the Entity Framework NuGet package and have at least one class defined in your project that is derived from the DbContext class. You also must have created a migration configuration class using the Enabe-Migration command. In addition you need to have created at least one migration using the Add-Migration command.

Sample 1 – Apply all changes to the database

Update-Database

Sample 2 – Create a script of all changes to the database

Update-Database -script
 

Enabling Migrations for a project with existing database

If you have an existing database and would like to start using code first you can use the following procedure to create an initial snapshot without making changes to the existing database. Once this can been set up you can then use migrations to drive changes in your DB based on the deltas in your C# classes.
  1. enable-migrations
  2. Add-Migration InitialCreate -IgnoreChanges
  3. update-database

© Copyright 2007 - 2016 Ciliberti Enterprises Corporation. All Rights reserved Reproduction in whole or in part without written permission is prohibited.
MyOnlineBand.com Version 5.2 updated 1/13/2017