Introduction
If you understand Code First Entity Framework then this article is easy to understand the concept of Code First Migration in Entity Framework. If you are unfamiliar with Code First then read this article Code First Entity Framework.
Code First Migration
You have created a database as per the domain requirements and you forgot a column that must exist in the table. You check and the column is not present. You then need not create and delete the existing model to add the new column or table in the database when this approach is used. Code First Migrations allow you to create a new database or update an existing database based on your model classes using the Package Manager Console for running commands.
If you are using the EF code first approach then there are more ways to initialize the database provided by the Entity Framework as follows.
- DropCreateDatabaseAlways. This database initializer class always drops and creates a new database, whether it is already present or not with every run of the application.
- DropCreateDatabaseWhenModelChanges. This database initializer class drops the existing database and re-creates it if there is a mismatch between the model classes and table schema.
- CreateDatabaseIfNotExists.
This class creates a database only if it doesn't exist. It avoids any accidental deletion of the database.
These three databases to be initialized are provided by EF fail when you are updating the model or classes and then it mismatches when it fails and your database records are lost. Here is one solution for this, EF Code First Migration. Using the approach you can change the model class or table or add new classes. Then no database records are lost and your existing database is also the same.
Creating Model and Database
For using this code first migration you need a database and code, first model. Use the procedure for creating the code first model.
- Open Microsoft Visual Studio.
- "File" -> "New" -> "Project...".
- Set the Console Application name as CodeFirstMigration.
- Click OK.
- Add the EntityFramework NuGet package.
- Tools -> Library Package Manager –> Package Manager Console
- Run the Install-Package EntityFramework command. See the output below:
See the following red color box that shows the added references for EntityFramework and database:
- Add a new class named EmployeeContext.cs to our Entity Framework Code First Context and add the following code. Code for EmployeeContext class file:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeFirstMigration
{
public class EmployeeContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
}
public class Employee
{
public int EmployeeID { get; set; }
public string EmpName { get; set; }
}
}
- Now we have a model. It's time to do some operation for data access. Add some code to the Program.cs file as in the following: Code for Program class file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeFirstMigration
{
class Program
{
static void Main(string[] args)
{
using (var context = new EmployeeContext())
{
//Insert values in database
context.Employees.Add(new Employee { EmployeeID = 1, EmpName = "krishna" });
context.Employees.Add(new Employee { EmployeeID = 2, EmpName = "radha" });
context.SaveChanges();
//Get all values from database
foreach (var emp in context.Employees)
{
Console.WriteLine("Employee ID : " + emp.EmployeeID);
Console.WriteLine("Employee Name : " + emp.EmpName);
}
}
Console.WriteLine("Press Any key to exit....");
Console.ReadKey();
}
}
}
- Save the changes and Run. The output is as in the following:
- See in the SQL Server and SQL Server Object Explorer your model CodeFirstMigration.EmployeeContext.
Until now we just created the model and added records to the database. The actual concept of Code First Migration is as follows.
- Make some more changes to our model. Add a new property Role to the Employees table.
public string Role { get; set; }
- Run the application. You will not get the error “InvalidOperationException” like the following:
- Now it's time to use the Code First Migration approach.
- Open Package Manager Console.
- Run Enable-Migrations command in a Package Manager console.
- This command added two more classes to your project in the Migrations folder.
- 201411061912454_InitialCreate.cs This migration was generated because Code First already created a database for us before we enabled migrations.
- Configuration.cs It allows you to configure how Migrations behave for your context.
- Update the database with the new changes we made in the model.
- Run Add-Migration MigrationForRoleInEmp in a Package Manager console.
Now it adds one more class to the Migrations folder in MigrationForRoleInEmp.cs. Let's use Update-Database to apply this migration to the database.
- Run the Update-Database command in a Package Manager console.
Code First Migrations will compare the migrations in our Migrations folder with the ones that have been applied to the database. It will see that the MigrationForRoleInEmp migration needs to be applied and run it. Finally, CodeFirstMigration.EmployeeContext database is now updated to include the Role column in the Employees table. See the following image:
Note: For detailed code please download the Zip file attached above.
Summary
I hope you understand Entity Framework Code First Migration. If you have any suggestion regarding this article then please contact me.