In this blog post we are going to learn about entity code first migrations. Entity Framework code first approach will allow you to define model classes as per the domain requirements via POCOs. Hence you have complete control over classes are written. But as application grows and there are some new features to be added and your classes will change. Entity Framework Code Migrations allows you to handle this migrations.
As we all now that Entity Framework Code First approach allows you to create database based on your classes created. It’s provide you three types of initializers.
CreateDatabaseIfNotExist: This is the default initializer which will create classes if database not exists.
DropCreateDatabasesWhenModelChanges: This initializer is only good when you don’t concern about your database records. If there is any change in class then it will match database will classes and if there is any difference then it will drop and create a new database.
DropCreateDatabaseAlways: This initializer will always create new database whether database exist or not. If database exist then it will drop that database and create it again.
Due to this initializers if we change our model classes and according to that your database will drop that is where Entity Framework code migrations will help. It will allows you to update your database based on classes change without dropping database.
For this walkthrough we are going to create a sample console application. I have create my entity like following.
Now it's time to add entity framework to console application. I have added entity framwork to console application via Tools – > Library Package Manager –> Package Manager Console and via running following command.
Install-Package EntityFramework
Now it’s time to create a blank database called Customer.
After adding EntityFramework, I have created a my CustomerDataContext like below.
So everything works fine. Now Let’s see our database. You can see there are two created. _MigrationHistory and Customer.
So you can see that Customer table create with three columns. Now our requirement changes a little bit. Now we want to add a Company field in Customer like so our mode class change like following.
So now if we run the application it will delete database and create it again. So let’s see how migration can be useful. Let’s first get familiar with two command of entity framework and then we will create a migration for company.
Enable-Migrations: This will enable migrations for the application and database.
Add-Migration : This command will scaffold the next migration based on changes you have made to your model since the last migration was created.
Update-Database: Will apply pending migration to database.
I have run following command in package-manager console.
Enable-Migrations
Add-Migration AddCompanyField
So it will create a migration folder and AddCompanyField Class. I have written code for it as following.
Update-Database
And it will create a company URL in Customer Table.
You can find source code for this application on github at following location.
https://github.com/dotnetjalps/Entity-Framework-Code-First-Sample
That’s it. Hope you like it. Stay tuned for more..
As we all now that Entity Framework Code First approach allows you to create database based on your classes created. It’s provide you three types of initializers.
CreateDatabaseIfNotExist: This is the default initializer which will create classes if database not exists.
DropCreateDatabasesWhenModelChanges: This initializer is only good when you don’t concern about your database records. If there is any change in class then it will match database will classes and if there is any difference then it will drop and create a new database.
DropCreateDatabaseAlways: This initializer will always create new database whether database exist or not. If database exist then it will drop that database and create it again.
Due to this initializers if we change our model classes and according to that your database will drop that is where Entity Framework code migrations will help. It will allows you to update your database based on classes change without dropping database.
Walkthrough of Entity Framework Code First Migration:
namespace EntityCodeFirstMigrations { public class Customer { public int CustomerId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } } }
Now it's time to add entity framework to console application. I have added entity framwork to console application via Tools – > Library Package Manager –> Package Manager Console and via running following command.
Install-Package EntityFramework
Now it’s time to create a blank database called Customer.
After adding EntityFramework, I have created a my CustomerDataContext like below.
using System.Data.Entity; namespace EntityCodeFirstMigrations { public class CustomerDataContext : DbContext { public CustomerDataContext() : base("CustomerConnectionString") { } public DbSet<Customer> Customers { get; set; } } }After creating a code following is code I have written in Console application main method.
using System; namespace EntityCodeFirstMigrations { class Program { static void Main(string[] args) { using (var dbContext = new CustomerDataContext()) { //Adding a customer dbContext.Customers.Add( new Customer { FirstName="Vishal", LastName="Vadgama" } ); dbContext.SaveChanges(); //Displaying Customer foreach (Customer customer in dbContext.Customers) { Console.WriteLine(customer.FirstName); Console.WriteLine(customer.LastName); Console.WriteLine("---------------"); } } } } }This code is pretty self explanatory. Here I have created a object of customer and added into the database with save changes method and then I have written a for loop for displaying customer values. Now your run the application it will show output as follows.
So everything works fine. Now Let’s see our database. You can see there are two created. _MigrationHistory and Customer.
So you can see that Customer table create with three columns. Now our requirement changes a little bit. Now we want to add a Company field in Customer like so our mode class change like following.
namespace EntityCodeFirstMigrations { public class Customer { public int CustomerId { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Company { get; set; } } }
So now if we run the application it will delete database and create it again. So let’s see how migration can be useful. Let’s first get familiar with two command of entity framework and then we will create a migration for company.
Enable-Migrations: This will enable migrations for the application and database.
Add-Migration : This command will scaffold the next migration based on changes you have made to your model since the last migration was created.
Update-Database: Will apply pending migration to database.
I have run following command in package-manager console.
Enable-Migrations
Add-Migration AddCompanyField
So it will create a migration folder and AddCompanyField Class. I have written code for it as following.
using System.Data.Entity.Migrations; namespace EntityCodeFirstMigrations.Migration { public partial class AddCompanyField : DbMigration { public override void Up() { AddColumn("dbo.Customers", "Company", c => c.String()); } public override void Down() { DropColumn("dbo.Customers", "Company"); base.Down(); } } }Now it's time to run update-database command like in package manager console.
Update-Database
And it will create a company URL in Customer Table.
You can find source code for this application on github at following location.
https://github.com/dotnetjalps/Entity-Framework-Code-First-Sample
That’s it. Hope you like it. Stay tuned for more..
Thanks jalpesh, very easy explanation.Would like to see more articles on entity framework.
ReplyDeleteI have already written few and continue to write more!! thanks for appreciation
Delete