Introduction
When working with Entity Framework Core in ASP.NET Core applications, generating DbContext and models is a crucial step. In this blog post, we'll explore three methods to simplify this process: using scaffolding commands, adhering to standard practices, and leveraging EF Core Power Tools in Visual Studio.
In this guide, we'll delve into the following three approaches to facilitate DbContext and model generation:
- Scaffolding Command in the console.
- Using standard methods.
- Utilizing EF Core Power Tools.
Method 1. Scaffolding Command
Step 1. Execute scaffolding command in Tools -- > NuGet Package Manager -- > Package Manager Console.
Step 2. Add the connection string directly.
scaffold-dbcontext -provider Microsoft.EntityFrameworkCore.SqlServer -connection "Data Source=(Server);Initial Catalog=(Database Name);UserId=(Username);Password=(Password);TrustServerCertificate=true;" -OutputDir Models
Step 3. Scaffold DbContext and models using the Scaffold-DbContext command.
Method 2. Standard Practices
Step 1. Add connection string in app.settings.json.
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=(Server Name);Initial Catalog=(Database Name);user id=(Username for connection on db);password=(Password);TrustServerCertificate=True;"
}
}
Step 2. Manually create a DbContext file. The class name should be ("DatabaseName"+Context.cs).
- NuGet Packages Required
- Microsoft.EntityFrameworkCore
- Microsoft.EntityFrameworkCore.SqlServe
- Microsoft.EntityFrameworkCore.Tools
using Microsoft.EntityFrameworkCore;
namespace BackEnd.Models //solution name models
{
//**The class name should be ("DatabaseName"+Context.cs)**
// database name = TryDbApproch.
// class name = TryDbApprochContext.cs.
public class TryDbApprochContext : DbContext
{
public TryDbApprochContext(DbContextOptions<TryDbApprochContext> options)
: base(options)
{
}
}
Step 3. Configure DbContext and connection string in program.cs.
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<TryDbApprochContext>(options =>
options.UseSqlServer(connectionString));
or
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<TryDbApprochContext>(options => options.UseSqlServer(connectionString, serverOptions =>
{
serverOptions.EnableRetryOnFailure(
maxRetryCount: 3, // Maximum number of retry attempts
maxRetryDelay: TimeSpan.FromSeconds(30), // Maximum delay between retries
errorNumbersToAdd: null); // Specific error numbers to retry on (null retries on all transient errors)
}));









Jon MyersPosted Jul 21, 2025, 3:04 PM
Hi, this has been really helpful but in method 2, step 3, I'm not sure what the builder object is - thought it might be A ConfigurationBuilder but that doesn't seem to have the Configuration or subsequent Services options so I'm a bit stuck? Thanks Jon
Digit PrincePosted Aug 28, 2024, 4:28 PM
Thank you for your articles.