In .Net 6, we can easily add a database connection to Entity FrameworkCore DbContext as below.
using EntityFrameworkCoreExample.Data.Context;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
var dbConnextionString = builder.Configuration.GetConnectionString("DBConnectionString");
builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(dbConnextionString));
Here DBConnectionString is the database connection string mentioned in appsettings.json as below.
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DBConnectionString": "Server=localhost;Database=Company;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}