Code First Approach In ASP.NET Core MVC With EF Core Migration

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

This article will help you to understand what the Code First approach is and how we can achieve it in ASP.NET Core MVC applications 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 the below steps while creating an ASP.NET Core MVC application in Visual Studio 2017.

  1. Open Visual Studio 2017
  2. Click on File> New > Project from the Menu
  3. In the New Project windows, from the left panel, select Installed Visual C#>Web
  4. Select the NET Core Web Application project template from the middle panel
  5. Enter CodeFirstMigrationas the name of the project and click OK
    EF Core Migration
  6. The next dialog will appear for the New ASP.NET Core Web Application.
  7. Choose the target framework as .NET Core and select the version from the drop-down as NET Core 2.0
  8. Select Web Application (Model-View-Controller) as a template
  9. Select the Authentication as 'No Authentication'
  10. Click OK
    Authentication

More articles on ASP.NET Core that 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. NET Core Web API with Oracle Database and Dapper

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

I hope the new application is running fine. Therefore, 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, that will help us to work with database-related activity like add migration, script migration, get dbcontext, update database, etc.

NuGet package

So far, we have created one Asp.Net Core MVC application and installed 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’s 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 is responsible for creating the tables in the database. 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)
        {
        }
        public DbSet<Employee> Employees { get; set; }
    }
}

As we, all know in the Code First approach, we first write the code, which means Model classes, and on 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 a 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")));
}

So far, we have done most of the things, like project creation, installing NuGet packages, creating Model classes, and setting connection strings. So, let's 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. CodeFirstMigration. Therefore, by default, it is a default project.

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

MigrationName

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 the add migration command with some name. Here you can see the 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 we've not created the actual database and tables. So, let's execute the migration script and generate the database and tables. Therefore, to execute the migration scripts we have to execute the ‘update-database’ command. So, let's perform it as follows.

For now, we have only one migration script available which 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 the command as follows.

Update-database migrationname

Database

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

Entity Framework Migration

Now, let's 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 the package manager console and run the following command to add a migration, this time we have given the name of the migration as 'addedsalary'.

Add-migration addedsalary

Once the above command execution is completed, it will create a new class for the migration name as follows. Here we can see, the migration builder has 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 the following command for updating the database.

Update-database addedsalary

Once the 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.

Employees table

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)
        {
        }
        public 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's add it to migration using the following command.

Add-migration seeddata

Once the above command executes successfully, we can see the following seed data class will be generated with insert data configuration. Here we are defining the table name in which data should be added, 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's update the database with the generated migration class using the following command.

Update-database seeddata

Once the above command is executed successfully in the Package Manager Console, just move to the database and refresh the table. You will find the same dummy data that we have defined in migration has been updated in the table.

Package Manager Console

Conclusion

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

I hope this post will help you. Please put your feedback using comments which helps me to improve myself for the 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