Auto Generate Dbcontext Class From Database In ASP.NET Core 3.1

Introduction

 
In this article, we will see how to auto-generate Dbcontext class for migration in asp.net core 3.1. Friends as we know, .net core 3.1 uses the code first approach for the Database connection. We can create simple tables from the code first approach using migration and can create explicit Dbcontext.cs for 1 or 2 tables, or a few tables. But when we have a complex database of the project having multiple foreign key relationships with multiple tables then it is much more difficult for creating a database using migration. So we want to generate our project database from a Database first approach and want to maintain it from migration easily. This problem can be solved by just a single command of Entity Framework Core tool.
 
Before applying migration in your project, make sure migration is already enabled, and all the packages have been installed in your project
 
Go to Nu Get Package Manager > install this package
 
Auto Generate Dbcontext class from database in Asp.net Core 3.1
 
Auto Generate Dbcontext class from database in Asp.net Core 3.1
 
Now, I have already created my complex database in SQL server with the name "db_Demo" , which has multiple tables with a foreign key relationship, so let's auto-generate its table model and a DbContext class. 
 
Go to View Menu> Other Windows> Package Manager Console > Write this Commond  
  1. Scaffold-DbContext "Server=MYSERVERNAME;Database=db_Demo;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Database -Context "ApplicationDbContext" -DataAnnotations    
 Parameter 1
  1. Scaffold-DbContext- Keyword for scaffold database  
 Parameter 2
  1. "Server=MYSERVERNAME;Database=db_Demo;Trusted_Connection=True;"  -Connection String     
Parameter 3
  1. Microsoft.EntityFrameworkCore.SqlServer -Package should be installed in your project  
 Parameter 4
  1. -OutputDir - The command that specifies the output directory name where all models created   
  Parameter 5
  1. Database- Folder Name    
  Parameter 6
  1. ApplicationDbContext - Name of DbContext class  
 If any modification performs in the database then alter models by this command.
  1. Scaffold-DbContext "Server=MYSERVERNAME;Database=db_Demo;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Database -Context "ApplicationDbContext" -DataAnnotations  -Force  
Output
 
All table models and ApplicationDbContext classes have been created.
 
Auto Generate Dbcontext class from database in Asp.net Core 3.1