In this article I will explain with an example, how to set
Entity Framework Core 6 DbContext Connection String.
Installing Entity Framework Core
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 Program 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.
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();