Creating EF6 Database Migration In Separate .Net Core Library

Introduction

 
Hii guys! In this article, we will discuss creating a data layered architecture pattern in asp.net core 3.1. Here, we will make a separate data layer library(.Net Core) for database connection and tables. And then add this library to our front MVC core website for dealing with the database.
 
As we all know that keeping our database separate from our website is a good practice and part of the onion pattern principle, so we are just trying to follow this rule. Here we will use EF6 Database Migrations tools for DbConnection and a few packages from manage nu get package manager.
 
So let’s see how we can implement this process.
 
Step 1
 
Create a new project in Visual Studio 2019> select Asp.Net Core Web Application>Provide the WebApplication Name (DemoDBMigration) and then select >create
During the creation of the project, please make sure that you have changed the authentication from "No Authentication" to "Individual User Accounts" for enabling migration in our project. 
 
 
Step 2
 
Now right click on solution explorer> go to the add New items>select Class library (.Net Core)>Next>Give it Name (DataLayer)>create
 
 
Step 3
 
Now for working with migration, we have to install a few Entity Framework Core packages from Manage Neu get Packages in the DataLayer library project.
 
Select DataLayer Project and go to the Manage Nuget Packages and install the below packages.
  1. Microsoft.AspNetCore.Identity(2.2.0)  
  2. Microsoft.AspNetCore.Identity.EntityFrameworkCore(3.1.5)  
  3. Microsoft. EntityFrameworkCore(3.1.5)  
  4. Microsoft. EntityFrameworkCore.Design(3.1.5)  
  5. Microsoft. EntityFrameworkCore.SqlServer(3.1.5)  
  6. Microsoft. EntityFrameworkCore.Tools(3.1.5)  
 
Step 4
 
Now create a folder named Models. In this folder, we will make all our database tables and ApplicationDbContext Class
 
Now before enabling migration in the DataLayer project, we have to set up the database connection string first. For doing this, we will add the DataLayer Project reference to the “DemoDBMigration “web project.
 
Setup a connection string in the appsettings.json (DemoDBMigration web project) file like this.
  1. "ConnectionStrings": {  
  2.     "DefaultConnection""Data Source=MYSQLSERVERNAME;Initial Catalog=db_DBMigration;User Id=MYUSERID; Password=MYPASSWORD"  
  3.   },  
And register the ApplicationDbContext Class in Startup.cs under the ConfigureServices method.
 
Startup.cs
  1. public void ConfigureServices(IServiceCollection services)  
  2.        {  
  3.            services.AddDbContext<ApplicationDbContext>(options =>  
  4.                options.UseSqlServer(  
  5.                    Configuration.GetConnectionString("DefaultConnection")));  
  6.   
  7.            services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)  
  8.                .AddEntityFrameworkStores<ApplicationDbContext>();  
  9.   
  10.            services.AddControllersWithViews();  
  11.            services.AddRazorPages();  
  12.        }  
Step 5
 
After setting up the proper connection string now, we are ready to enable migration in our DataLayer project.
 
Note
Don’t forget to create a blank database first to the SQL server. And delete a Data folder from the Web Project (DemoDBMigration project) if it already exists, otherwise, it throws an error of “No 2 DbContext class can create migration”.
 
Create an ApplicationDbContext.cs in Models folder. 
  1. using Microsoft.AspNetCore.Identity.EntityFrameworkCore;  
  2. using Microsoft.EntityFrameworkCore;  
  3. using Microsoft.Extensions.Configuration;  
  4. using System;  
  5. using System.Collections.Generic;  
  6. using System.Linq;  
  7. using System.Text;  
  8. namespace DataLayer  
  9. {  
  10.     public class ApplicationDbContext : IdentityDbContext  
  11.     {  
  12.         public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)  
  13.           : base(options)  
  14.         { }  
  15.         public DbSet<Category> Category { getset; }  
  16.         public IConfiguration Configuration { get; }  
  17.     }  
  18. }  
Category.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.ComponentModel.DataAnnotations.Schema;  
  5. using System.Text;  
  6.   
  7. namespace DataLayer  
  8. {  
  9.     public class Category  
  10.     {  
  11.         [Key]  
  12.         [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
  13.         public int Id { getset; }  
  14.         public string Name { getset; }  
  15.         public int DisplayOrder { getset; }  
  16.         public bool IsActive { getset; }  
  17.     }  
  18. }  
Go to View menus> Other Windows>select Package Manager Console
 
Select DataLayer  project as Default Project over the Package Manager Console.  And for adding migration write the following command here.
  1. PM> add-migration initial  
Look that the project Migration folder is created automatically.
 
Now for moving identity tables and our table into the database let's follow the below command.
  1. PM> update-database  
 
Now check the Database, all the tables with the identity tables are auto-created.
 
 
Step 6
 
We can access it by injecting ApplicationDBContext class in the constructor of the controller.
  1. public class AccountController : Controller  
  2.    {  
  3.        private readonly ApplicationDbContext db;  
  4.        public AccountController(ApplicationDbContext db)  
  5.        {  
  6.            this.db = db;  
  7.        }  
  8.        public IActionResult Index()  
  9.        {  
  10.            var categories = db.Category.ToList();  
  11.            return View();  
  12.        }  
  13.    }  
OutPut
 
 

Summary

 
In this article, I have discussed how we can create a layered architecture. We also saw how to make a separate library for database and how to enable migration with all identity classes. Furthermore, we saw how to generate a database from migration. At last, we saw how to use access database tables over the web layer.