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

Code First is a technique which helps us to create a database, 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 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 to File> New > Project from the Menu
  3. In 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

    Code First Approach in Asp.Net Core MVC with EF Core Migration
  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 drop-down as NET Core 2.0
  3. Select Web Application (Model-View-Controller) as a template
  4. Select the Authentication as 'No Authentication'
  5. Click OK

    Code First Approach in Asp.Net Core MVC with EF Core Migration

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

Code First Approach in Asp.Net Core MVC with EF Core Migration

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.

Code First Approach in Asp.Net Core MVC with EF Core Migration

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.

  1. namespace CodeFirstMigration.Context  
  2. {  
  3.     public class Employee  
  4.     {  
  5.         public int EmployeeId { get; set; }  
  6.         public string Name { get; set; }  
  7.         public string Address { get; set; }  
  8.         public string CompanyName { get; set; }  
  9.         public string Designation { get; set; }  
  10.     }  
  11. }  

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. 

  1. using Microsoft.EntityFrameworkCore;  
  2.   
  3. namespace CodeFirstMigration.Context  
  4. {  
  5.     public class EmployeeDbContext : DbContext  
  6.     {  
  7.         public EmployeeDbContext(DbContextOptions options) : base(options)  
  8.         {  
  9.         }  
  10.   
  11.         DbSet<Employee> Employees { get; set; }  
  12.     }  
  13. }  

As w, all know that 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 connection string inside the appsetting.json file as follows.

  1. {  
  2.   "Logging": {  
  3.     "IncludeScopes"false,  
  4.     "LogLevel": {  
  5.       "Default""Warning"  
  6.     }  
  7.   },  
  8.   "ConnectionStrings": {  
  9.     "myconn""server=ABC\\SQLEXPRESS2012; database=EmployeeDB;Trusted_Connection=True;"  
  10.   }  
  11. }  

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

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

So far, we have done most of the things, like project creation, installing NuGet packages, creating Model classes and setting connection string. 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 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.

Code First Approach in Asp.Net Core MVC with EF Core Migration

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 the table structure based on your Model (Employee), which is ready to generate the database

  1. using Microsoft.EntityFrameworkCore.Metadata;  
  2. using Microsoft.EntityFrameworkCore.Migrations;  
  3.   
  4. namespace CodeFirstMigration.Migrations  
  5. {  
  6.     public partial class initialmigration : Migration  
  7.     {  
  8.         protected override void Up(MigrationBuilder migrationBuilder)  
  9.         {  
  10.             migrationBuilder.CreateTable(  
  11.                 name: "Employees",  
  12.                 columns: table => new  
  13.                 {  
  14.                     EmployeeId = table.Column<int>(nullable: false)  
  15.                         .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),  
  16.                     Name = table.Column<string>(nullable: true),  
  17.                     Address = table.Column<string>(nullable: true),  
  18.                     CompanyName = table.Column<string>(nullable: true),  
  19.                     Designation = table.Column<string>(nullable: true)  
  20.                 },  
  21.                 constraints: table =>  
  22.                 {  
  23.                     table.PrimaryKey("PK_Employees", x => x.EmployeeId);  
  24.                 });  
  25.         }  
  26.   
  27.         protected override void Down(MigrationBuilder migrationBuilder)  
  28.         {  
  29.             migrationBuilder.DropTable(  
  30.                 name: "Employees");  
  31.         }  
  32.     }  
  33. }  

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, executing the migration scripts we have to execute ‘update-database’ command. So, let's perform it as follows. 

For now, we have only one 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

Code First Approach in Asp.Net Core MVC with EF Core Migration

Once the above command executes successfully, we 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. 

Code First Approach in Asp.Net Core MVC with EF Core Migration

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

  1. namespace CodeFirstMigration.Context  
  2. {  
  3.     public class Employee  
  4.     {  
  5.         public int EmployeeId { get; set; }  
  6.         public string Name { get; set; }  
  7.         public string Address { get; set; }  
  8.         public string CompanyName { get; set; }  
  9.         public string Designation { get; set; }  
  10.         public float Salary { get; set;  }  
  11.     }  
  12. }  

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 the above command execution will be completed, it will create a new class for migration name as follows. Here we can see, migration builder has the configuration for adding a new column as salary.

  1. using Microsoft.EntityFrameworkCore.Migrations;  
  2.   
  3. namespace CodeFirstMigration.Migrations  
  4. {  
  5.     public partial class addedsalary : Migration  
  6.     {  
  7.         protected override void Up(MigrationBuilder migrationBuilder)  
  8.         {  
  9.             migrationBuilder.AddColumn<float>(  
  10.                 name: "Salary",  
  11.                 table: "Employees",  
  12.                 nullable: false,  
  13.                 defaultValue: 0f);  
  14.         }  
  15.   
  16.         protected override void Down(MigrationBuilder migrationBuilder)  
  17.         {  
  18.             migrationBuilder.DropColumn(  
  19.                 name: "Salary",  
  20.                 table: "Employees");  
  21.         }  
  22.     }  
  23. }  

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.

Code First Approach in Asp.Net Core MVC with EF Core Migration

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.

  1. using Microsoft.EntityFrameworkCore;  
  2.   
  3. namespace CodeFirstMigration.Context  
  4. {  
  5.     public class EmployeeDbContext : DbContext  
  6.     {  
  7.         public EmployeeDbContext(DbContextOptions options) : base(options)  
  8.         {  
  9.         }  
  10.   
  11.         DbSet<Employee> Employees { get; set; }  
  12.   
  13.         protected override void OnModelCreating(ModelBuilder modelBuilder)  
  14.         {  
  15.             modelBuilder.Entity<Employee>().HasData(  
  16.                 new Employee() { EmployeeId = 1, Name = "John", Designation = "Developer", Address = "New York", CompanyName = "XYZ Inc", Salary = 30000 },  
  17.                 new Employee() { EmployeeId = 2, Name = "Chris", Designation = "Manager", Address = "New York", CompanyName = "ABC Inc", Salary = 50000 },  
  18.                 new Employee() { EmployeeId = 3, Name = "Mukesh", Designation = "Consultant", Address = "New Delhi", CompanyName = "XYZ Inc", Salary = 20000 });  
  19.         }  
  20.     }  
  21. }  

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

  1. using Microsoft.EntityFrameworkCore.Migrations;  
  2.   
  3. namespace CodeFirstMigration.Migrations  
  4. {  
  5.     public partial class seeddata : Migration  
  6.     {  
  7.         protected override void Up(MigrationBuilder migrationBuilder)  
  8.         {  
  9.             migrationBuilder.InsertData(  
  10.                 table: "Employees",  
  11.                 columns: new[] { "EmployeeId""Address""CompanyName""Designation""Name""Salary" },  
  12.                 values: new object[] { 1, "New York""XYZ Inc""Developer""John", 30000f });  
  13.   
  14.             migrationBuilder.InsertData(  
  15.                 table: "Employees",  
  16.                 columns: new[] { "EmployeeId""Address""CompanyName""Designation""Name""Salary" },  
  17.                 values: new object[] { 2, "New York""ABC Inc""Manager""Chris", 50000f });  
  18.   
  19.             migrationBuilder.InsertData(  
  20.                 table: "Employees",  
  21.                 columns: new[] { "EmployeeId""Address""CompanyName""Designation""Name""Salary" },  
  22.                 values: new object[] { 3, "New Delhi""XYZ Inc""Consultant""Mukesh", 20000f });  
  23.         }  
  24.   
  25.         protected override void Down(MigrationBuilder migrationBuilder)  
  26.         {  
  27.             migrationBuilder.DeleteData(  
  28.                 table: "Employees",  
  29.                 keyColumn: "EmployeeId",  
  30.                 keyValue: 1);  
  31.   
  32.             migrationBuilder.DeleteData(  
  33.                 table: "Employees",  
  34.                 keyColumn: "EmployeeId",  
  35.                 keyValue: 2);  
  36.   
  37.             migrationBuilder.DeleteData(  
  38.                 table: "Employees",  
  39.                 keyColumn: "EmployeeId",  
  40.                 keyValue: 3);  
  41.         }  
  42.     }  
  43. }  

So, let's 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.

Code First Approach in Asp.Net Core MVC with EF Core Migration

Conclusion

So, today we have learned how to implement the 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