Asp.Net MVC and Entity Framework Database Migrations using CodeFirst

Database migrations using EF CodeFirst commands inside Package Manager Console.

 

Posted: April 25, 2017. | By: mustafa

Entity Framework CodeFirst makes use of POCO model. Using POCO model we can generate database from model classes. This gives developer freedom to concentrate on Business Domain.

This also supports attributed based mapping from classes to table. One could also use the Fluent API to configure relationship between entities and objects.

Here in this article I am going to explain how to use codefirst in your Asp.Net Mvc project to migrate database using Entity Framework.

Start an empty Asp.Net Mvc project name TestWeb and install Entity Framework to be able to use CodeFirst in this project. Go to Tools menu select Library Package Manager and then select Package Manager Console.

PackageManagerConsole.png, Entity Framework, CodeFirst, DB Migration,

A console window will open use command to install command update Entity Framework.

PM> Install-Package EntityFramework
Now let us add a simple model class UserProfile.cs

public class UserProfile
 {
 [Key]
 public int UserProfileId { get; set; }
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public string MobileAlias { get; set; }
 public string Address { get; set; }

}


Add the key attribute to the UserProfileId property to make it a Primary or Unique Key to identify the record. There are some conventions CodeFirst follows to update the database.

The most important part is to add our Context class. Lets add class TestWebContext inheriting from DbContext class. In this class we override OnModelCreating() method. DbSet is a set of entities defined using model classes.

public class TestWebContext : DbContext
 {
 public TestWebContext()
 : base("name=TestWebDbContext")
 {
 }
 
 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
 //throw new UnintentionalCodeFirstException();
 }

public DbSet<TestWeb.WebApp.Models.UserProfile> UserProfile { get; set; }
 }


 

As we know EF CodeFirst approach follows convention over configuration so we are have added a constructor passing the connectionString name as same as defined in web.config.

Adding connection string in our web.config

<add name="TestWebDbContext" connectionString="data source=localhost;initial catalog=CodeFirstDB;user id=username;password=password;MultipleActiveResultSets=True;App=EntityFramework;Timeout=60;" providerName="System.Data.SqlClient"/>

 

Now we are going to update our database using CodeFirst commands in Package Manager Console.

PM> Enable-migrations
Enabling database migrations creates a new folder in our solution in Visual Studio. Adding a Configuration.cs file containing default settings. We update the file setting AutomaticMigrationEnabled property to true and add AutomaticMigrationDataLossAllowed to false. That means during migration no data is loss in our existing tables.

using System;
    using System.Data.Entity;
    using System.Data.Entity.Migrations;
    using System.Linq;

    internal sealed class Configuration : DbMigrationsConfiguration<TestWeb.WebApp.Models.TestWebContext>
    {
        public Configuration()
        {
            AutomaticMigrationsEnabled = true;
            AutomaticMigrationDataLossAllowed = false;
        }

        protected override void Seed(TestWeb.WebApp.Models.TestWebContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method 
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
        }
    }

 

To update the database use following command at PM> prompt.
PM> Update-Database -Verbose

Verbose flag here specifies to display sql commands being applied to the target database.

UpdateDatabase.png, Entity Framework, CodeFirst, DB Migration,

Now open Sql Server in Management Studio and refresh the Database node to see the new database CodeFirstDB is created and verify table UserProfiles containing primary key UserProfileId.

CodeFirstDB.png, Entity Framework, CodeFirst, DB Migration,


related posts

Back to top