Code First is a technique which helps us to create a database, migrates and maintaining the database and its tables from the code. From the code, means, you directly maintain the database and its corresponding tables from the .Net Code. It is helpful when you don’t have database ready and you want to start working with new fresh project and want to create a database and maintain database directly from your code.

This article will help you to understand what Code First approach is and how we can achieve it in Asp.Net Core MVC application using Entity Framework Core migration. Migration always helps us to create, update and sync the database with your model classes. In this demonstration, we will understand the Entity Framework Core migration step by step practically. So, let's create a new application for the demonstration.

Let us jump to Visual Studio 2017 and create a new Asp.Net Core MVC application. You can follow below steps while creating an Asp.Net Core MVC application in Visual Studio 2017.

  1. Open Visual Studio 2017
  2. Click to File > New > Project from the Menu
  3. In New Project windows, from the left panel,  select Installed Visual C# > Web
  4. Select the ASP.NET Core Web Application project template from the middle panel
  5. Enter CodeFirstMigration as the name of the project and click OK

Asp.Net Core MVC

 

  1. Next dialog will appear for the New ASP.NET Core Web Application.
  2. Choose the target framework as .Net Core and select the version from the dropdown as Asp.Net Core 2.0
  3. Select Web Application (Model-View-Controller) as a template
  4. Select the Authentication as 'No Authentication'
  5. Click OK

Asp.Net Core Web Application

 

MORE ARTICLES ON ASP.NET CORE WHICH YOU MAY LIKE.
  1. First Application in Asp.Net Core MVC 2.0
  2. 10 New Features of Asp.Net Core 2.0
  3. Publish Asp.Net Core 2.0 Application on IIS
  4. Getting started with Razor Pages in Asp.Net Core 2.0
  5. ASP.NET Core Web API with Oracle Database and Dapper

Now we have the project ready. You can check it to run the application using press F5. If everything is well then we can move forward.

Hope, the new application is running fine. So, next, we will install some of the required Entity Framework Core packages from the NuGet Package Manager for performing database operations from the code.  First, we will install the package like Microsoft.EntityFrameworkCore.SqlServer which will provide classes to connect with SQL Server for CRUD Operation to Entity Framework Core.

Entity Framework Core

The second required NuGet package is Microsoft.EntityFrameworkCore.Tools which will help us to work with database related activity like add migration, script migration, get dbcontext, update database etc.

Entity Framework Core

Till now, we have created one Asp.Net Core MVC application and install some required Entity Framework Core packages which are required for Code First migration or we can say, these will help us to use Entity Framework Core functionality for working with SQL Server.

So, let move and create a folder name as ‘Context’ and create a Model class as ‘Employee’ in this with the following properties as follows.

namespace CodeFirstMigration.Context
{
    public class Employee
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string CompanyName { get; set; }
        public string Designation { get; set; }
    }
}

We will create another class inside the Context folder as ‘EmployeeDbContext’ that will inherit to DbContext class. This class will contain all the model's information which are responsible for creating the tables in the databae. Here we will define our Employee class as DbSet

using Microsoft.EntityFrameworkCore;

namespace CodeFirstMigration.Context
{
    public class EmployeeDbContext : DbContext
    {
        public EmployeeDbContext(DbContextOptions options) : base(options)
        {
        }

        DbSet<Employee> Employees { get; set; }
    }
}

As we, all know that in the Code First approach, we first write the code, means Model classes and the basis of these classes our tables are auto-generated inside the database. However, to create these tables in the database we have to define our connection string where we will define our server and database name. For this demonstration, we are not using SQL Windows Authentication but you can use Mixed Authentication and pass the username and password with the connection string. So, you can write connection string inside the appsetting.json file as follows.

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "ConnectionStrings": {
    "myconn": "server=ABC\\SQLEXPRESS2012; database=EmployeeDB;Trusted_Connection=True;"
  }
}

To use this connection string, first, we will change the ConfigureServices method in Startup.cs class as follows. 

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();
    services.AddDbContext<EmployeeDbContext>(item => item.UseSqlServer(Configuration.GetConnectionString("myconn")));
}

Till yet, we have done most of the things, like project creation, installing NuGet packages, creating Model classes and setting connection string. So, let generate the database using Entity Framework Core Migrations.

Open Package Manager Console from the Tools Menu and select the Default project for which you would like to generate migrations code. For this demonstration, we have only a single project as CodeFirstMigration. Therefore, by default, it is a default project.

For creating the migration code, we use ‘add-migration MigrationName’ command. So, let’s perform this operation and see what happens. Therefore, in the Package Manager Console, just type ‘add-migration initialmigration command and press Enter.

Add migration in entity framework

Once the add migration command executes successfully, it creates a folder name as ‘Migration’ in the project and creates the class with the same name [MigrationName] as we have provided while executing add migration command with some name. Here you can see table structure based on your Model (Employee), which is ready to generate the database

using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;

namespace CodeFirstMigration.Migrations
{
    public partial class initialmigration : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "Employees",
                columns: table => new
                {
                    EmployeeId = table.Column<int>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    Name = table.Column<string>(nullable: true),
                    Address = table.Column<string>(nullable: true),
                    CompanyName = table.Column<string>(nullable: true),
                    Designation = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_Employees", x => x.EmployeeId);
                });
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "Employees");
        }
    }
}

We have only created the migration script which is responsible for creating the database and its table. But not created the actual database and tables. So, let execute the migration script and generate the database and tables. Therefore, executing the migration scripts we have to execute ‘update-database’ command. So, let perform it as follows. 

For now, we have only once migration script available that is why we are not providing the name of the migration. If we have multiple migration scripts, then we have to provide the name along with command as follows.

update-database migrationname

Add migration in entity framework

Once the above command executes successfully, just need to go to SQL Server Management Studio and login with Windows Authentication and see the Database. You will find the database, table and Entity Framework Migration history table as follows. 

EF Core Migration with Code First

 

Now, let modify the Employee model and add a new property as Salary with float type as follows.

namespace CodeFirstMigration.Context
{
    public class Employee
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public string CompanyName { get; set; }
        public string Designation { get; set; }
        public float Salary { get; set;  }
    }
}

Move to package manager console and run the following command to add migration, this time we have given the name of migration as 'addedsalary'.

add-migration addedsalary

Once above command execution will be completed, it will create a new class for migration name as follows. Here we can see, migration builder have the configuration for adding a new column as salary.

using Microsoft.EntityFrameworkCore.Migrations;

namespace CodeFirstMigration.Migrations
{
    public partial class addedsalary : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<float>(
                name: "Salary",
                table: "Employees",
                nullable: false,
                defaultValue: 0f);
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropColumn(
                name: "Salary",
                table: "Employees");
        }
    }
}

For updating the table in the database with the new column as salary, we have to run following command for updating the database.

update-database addedsalary

Once above update database command will execute successfully, just check the database's table. You will find the new column has been added to the Employees table as salary.

EF Core Migration with Code First

 

Now, let's see how to seed some dummy data into the table. So, move to EmployeeDbContext class and override the DbContext method 'OnModelCreating'. Using the help of the ModelBuilder, we can add some dummy data for the Employees table as follows.

using Microsoft.EntityFrameworkCore;

namespace CodeFirstMigration.Context
{
    public class EmployeeDbContext : DbContext
    {
        public EmployeeDbContext(DbContextOptions options) : base(options)
        {
        }

        DbSet<Employee> Employees { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Employee>().HasData(
                new Employee() { EmployeeId = 1, Name = "John", Designation = "Developer", Address = "New York", CompanyName = "XYZ Inc", Salary = 30000 },
                new Employee() { EmployeeId = 2, Name = "Chris", Designation = "Manager", Address = "New York", CompanyName = "ABC Inc", Salary = 50000 },
                new Employee() { EmployeeId = 3, Name = "Mukesh", Designation = "Consultant", Address = "New Delhi", CompanyName = "XYZ Inc", Salary = 20000 });
        }
    }
}

So, above we have already prepared the data for seeding. Now, let add it to migration using the following command.

 add-migration seeddata

Once the above command will execute successfully, we can see the following seeddata class will be generated with insert data configuration. Here we are defining table name in which data should add, columns and their respective values.

 

using Microsoft.EntityFrameworkCore.Migrations;

namespace CodeFirstMigration.Migrations
{
    public partial class seeddata : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.InsertData(
                table: "Employees",
                columns: new[] { "EmployeeId", "Address", "CompanyName", "Designation", "Name", "Salary" },
                values: new object[] { 1, "New York", "XYZ Inc", "Developer", "John", 30000f });

            migrationBuilder.InsertData(
                table: "Employees",
                columns: new[] { "EmployeeId", "Address", "CompanyName", "Designation", "Name", "Salary" },
                values: new object[] { 2, "New York", "ABC Inc", "Manager", "Chris", 50000f });

            migrationBuilder.InsertData(
                table: "Employees",
                columns: new[] { "EmployeeId", "Address", "CompanyName", "Designation", "Name", "Salary" },
                values: new object[] { 3, "New Delhi", "XYZ Inc", "Consultant", "Mukesh", 20000f });
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DeleteData(
                table: "Employees",
                keyColumn: "EmployeeId",
                keyValue: 1);

            migrationBuilder.DeleteData(
                table: "Employees",
                keyColumn: "EmployeeId",
                keyValue: 2);

            migrationBuilder.DeleteData(
                table: "Employees",
                keyColumn: "EmployeeId",
                keyValue: 3);
        }
    }
}

So, let update the database with generated migration class using the following command.

update-database seeddata

Once the above command will execute successfully in Package Manager Console, just move to the database and refresh the table. you will find the same dummy data which we have defined in migration has been updated into the table.

Seed Data in entity framework core

Conclusion

So, today we have learned how to implement code first approach in Asp.Net Core MVC project using Entity Framework Core Migration.

I hope this post will help you. Please put your feedback using comment which helps me to improve myself for next post. If you have any doubts please ask your doubts or query in the comment section and If you like this post, please share it with your friends. Thanks