Dot Net For All

Entity Framework Migration and Synchronization

In  my previous article I have showed how we can create a database using the code first approach in Entity Framework. But there is more then this in Entity framework. Suppose we have to keep the database updated with the changes in the class or update the data in the database. We should use the migration and synchronizing techniques which Entity Framework provides. Here I will discuss these techniques with code examples.

Entity Framework Migration

Migration is the feature of the Entity Framework that allow us to change the schema of data base. It also allows us to add default data in the database all with C# code.

Please note that I am using the previous article code example only.

Open console manager by Tools > Nuget Package Manager > Package Manager Console, Type “Enable-Migrations -ContextTypeName EmployeeDb” and enter.

This command will check if the project is already connected to a database. It will create a new folder named Migrations in the project . This folder has a file named Configurations.cs. This class is about controlling the migration. When migration should run , what data it should insert and all these complexities.

In the constructor of the Configuration class, AutomaticMigrationsEnabled is set as false. This denotes that migrations are not run automatically. This is helpful if the project is completed and we are final with our class design and structures. We will set it as true as we need to do the changes.

The other thing about this class is the Seed method which is used to add the initial data to database. The code for the whole class is as shown below

internal sealed class Configuration : DbMigrationsConfiguration<WpfApplication_EntityFramework.Model.EmployeeDb>
    {
        public Configuration()
        {
             AppDomain.CurrentDomain.SetData("DataDirectory",
                              Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData));
            AutomaticMigrationsEnabled = true;
        }

        protected override void Seed(WpfApplication_EntityFramework.Model.EmployeeDb context)
        {
            context.Employee.AddOrUpdate(new Model.Employee()
            {
                FirstName = "Vikram",
                LastName = "Chaudhary",
                Reviews = new List<EmployeeReview>()
                {
                    new EmployeeReview() {Review = "Good", ReviewerName = "Manager" } ,
                    new EmployeeReview() {Review = "Great", ReviewerName = "Manager1" }
                }
            }, new Employee()
            {
                FirstName = "Mukesh",
                LastName = "Kumar",
                Reviews = new List<EmployeeReview>()
                {
                    new EmployeeReview() {Review = "Excellent", ReviewerName = "Manager" } ,
                    new EmployeeReview() {Review = "Great", ReviewerName = "Manager1" }
                }
            });
        }

In the above code I have used AddOrUpdate to prevent from data duplication. If we are running this code multiple times we should not add the same record. While updating if EF finds that data is already present it only updates the data. For each employee I have added employee reviews.

Now to update this data we should run “Update-Database -verbose” in package manager console.

As we can see in the above figure when we run the command it checks for any pending changes. It also runs the seed method which inserts the initial data in our case.

We can see the data in the tables as shown in the figure below. The tables is EmployeeReview. In this table we can see the foreign key also which is related to Employee Table.

Now if you want to change the structure of the EmployeeReview class. Add a new integer field named Rating to the class code. This change you want to migrate to the database. Run the command “Update-Database -verbose” in the console manager. As shown in the below figure you can see the changes being made to the EmployeeReviews Table.

Please be aware that since the above command is executed after changes to schema. Whole of data is inserted once more in the tables from the seed method.

If you want to create the scripts for all of the data base migration you can use “Update-Database -Script -SourceMigration: $InitialDatabase” command. It will create a SQL script for whole schema.

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview