To generate models and DbContext automatically from the SQL server or Azure SQL database, we could use the Microsoft.EntityFrameworkCore.Design
package and the Microsoft.EntityFrameworkCore.SqlServer
database provider.
You can refer to the following methods:
Create an Asp.net core application and add the connection string in the appsettings.json file, like this:
Method 1: using .Net Core CLI command.
1.Right click the project and select the "open in terminal" option.
2.In the terminal window, use the following command to install the EF core tools:
dotnet tool install --global dotnet-ef
like this:
3.Use the following commands to install the Microsoft.EntityFrameworkCore.Design
package and the Microsoft.EntityFrameworkCore.SqlServer
database provider:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer --version 7.0.9
dotnet add package Microsoft.EntityFrameworkCore.Design --version 7.0.9
4.Finally, use the following command to generate the models and dbcontext:
dotnet ef dbcontext scaffold "Name=ConnectionStrings:dbcontectstring" Microsoft.EntityFrameworkCore.SqlServer -o Models -c BlogContext
Method 2: Using the Package Manager Console
1.Open the Package Manager Console and use the following commands to install the related package:
NuGet\Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 7.0.9
NuGet\Install-Package Microsoft.EntityFrameworkCore.Design -Version 7.0.9
NuGet\Install-Package Microsoft.EntityFrameworkCore.Tools -Version 7.0.9
2.Then, use the following command to add the Models and Context
Scaffold-DbContext 'Name=ConnectionStrings:dbcontectstring' Microsoft.EntityFrameworkCore.SqlServer -context ApplicationDbContext -OutputDir Models
The output like this:
More detail information about the .Net Core CLI or Scaffold-DbContext
commands, see:
Entity Framework Core tools reference - Package Manager Console in Visual Studio
Entity Framework Core tools reference - .NET Core CLI
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.
Best regards,
Dillion