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
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
- Scaffold-DbContext "Server=MYSERVERNAME;Database=db_Demo;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Database -Context "ApplicationDbContext" -DataAnnotations
Parameter 1
- Scaffold-DbContext- Keyword for scaffold database
Parameter 2
- "Server=MYSERVERNAME;Database=db_Demo;Trusted_Connection=True;" -Connection String
Parameter 3
- Microsoft.EntityFrameworkCore.SqlServer -Package should be installed in your project
Parameter 4
- -OutputDir - The command that specifies the output directory name where all models created
Parameter 5
- ApplicationDbContext - Name of DbContext class
If any modification performs in the database then alter models by this command.
- 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.