In this article I will explain with an example, how to set Entity Framework Core 6 DbContext Connection String.
Note: For beginners in ASP.Net Core 6, please refer my article ASP.Net Core 6: Hello World Tutorial with Sample Program example.
 
 
Installing Entity Framework Core
For more details on installing EntityFrameworkCore, please refer my article .Net Core 6: Install Entity Framework Core 6.
 
 
Adding the Connection String inside AppSettings.json
The following Connection String setting has been added in the AppSettings.json file.
{
 "ConnectionStrings": {
     "MyConn""Data Source=.\\SQL2022;Initial Catalog=Northwind;Integrated security=true"
 }
}
 
 
Database Context
1. Now you will need to add a new class to your project by right clicking on the Solution Explorer and then click on Add and then New Item option of the Context Menu.
2. Inside the class, first inherit the EntityFrameworkCore namespace and then inherit the DbContext class.
Then, using Dependency Injection, a Constructor is created DbContextOptions are passed as parameter and also the Constructor of base class i.e. DbContext class is inherited.
using Microsoft.EntityFrameworkCore;
 
namespace EF_Core_6_MVC
{
    public class DBCtx : DbContext
    {
        public DBCtx(DbContextOptions<DBCtx> options) : base(options)
        {
        }
    }
}
 
 
Setting DbContext Connection String in Startup class
Inside the Program.cs file, the Connection String is read from the AppSettings.json file and is used to add the DbContext service to the WebApplicationBuilder class.
Note: For more details on reading Connection String inside the Program.cs file, please refer my article .Net Core 6: Read Connection String inside Program.cs from AppSettings.json file.
 
using EF_Core_6_MVC;
using Microsoft.EntityFrameworkCore;
 
var builder = WebApplication.CreateBuilder(args);
 
// Enabling MVC
builder.Services.AddControllersWithViews();
string conStr = builder.Configuration.GetSection("ConnectionStrings")["MyConn"];
// Setting DbContext Connection String.
builder.Services.AddDbContext<DBCtx>(options => options.UseSqlServer(conStr));
 
var app = builder.Build();
 
//Configuring Routes
app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
 
app.Run();
 
Note: For more details, please refer my article ASP.Net Core 6: Simple Entity Framework Tutorial with example.


Other available versions