I am Utpal Vishwas from Uttar Pradesh. Have completed my B. Tech. course from MNNIT campus Prayagraj in 2022. I have good knowledge of computer networking.
Registering it in the Program.cs (or
Startup.cs for older versions)
Specifying a connection string and provider (e.g., SQL Server)
Step-by-Step: Configuring a DbContext
1. Create a Model
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
2. Create the DbContext
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options) { }
public DbSet<Product> Products { get; set; }
}
var builder = WebApplication.CreateBuilder(args);
// Register DbContext with SQL Server
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
var app = builder.Build();
// ... app.UseRouting(), app.MapControllers(), etc.
app.Run();
For other databases:
Use .UseSqlite(), .UseNpgsql(), .UseMySql(), etc.
Done! You can now inject AppDbContext anywhere:
public class ProductService
{
private readonly AppDbContext _context;
public ProductService(AppDbContext context)
{
_context = context;
}
public List<Product> GetAll() => _context.Products.ToList();
}
Summary
Task
How to do it
Define the context
Inherit from DbContext
Register in DI
builder.Services.AddDbContext
Set the connection string
In appsettings.json
Use in app
Inject via constructor
Join MindStick Community
You need to log in or register to vote on answers or questions.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
In ASP.NET Core, you configure a
DbContextby:DbContextProgram.cs(orStartup.csfor older versions)Step-by-Step: Configuring a
DbContext1. Create a Model
2. Create the DbContext
3. Add Connection String in
appsettings.json4. Register DbContext in
Program.cs(.NET 6/7/8)Done! You can now inject
AppDbContextanywhere:Summary
DbContextbuilder.Services.AddDbContextappsettings.json