In this article I will explain with an example, how to set Connection String inside OnConfiguring method in DbContext class in ASP.Net Core.
Database
Here I am making use of Microsoft’s Northwind database. You can download it from here.
Model
The Model class consists of following properties.
public class Customer
{
public string CustomerID { get; set; }
public string ContactName { get; set; }
public string City { get; set; }
public string Country { get; set; }
}
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
Once the
Entity Framework is configured and connected to the database table, the Database Context will look as shown below.
Setting Connection String inside OnConfiguring method
The OnConfiguring override method is used to configure the database (and other options) for DbContext. This method is called for each instance of the context that is created.
Inside OnConfiguring method a check is performed if the options have already been set, if the DbContextOptionsBuilder hasn't been set, then the Connection String is read from the AppSettings.json file and is used to set to the DbContextOptionsBuilder class using UseSqlServer method.
using ConnectionString_OnConfiguration_Core_7.Models;
using Microsoft.EntityFrameworkCore;
namespace ConnectionString_OnConfiguration_Core_7
{
public class DBCtx : DbContext
{
public DBCtx(DbContextOptions<DBCtx> options) : base(options)
{
}
public DbSet<Customer> Customers { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
// Read connection from appsettings.json.
optionsBuilder.UseSqlServer(WebApplication.CreateBuilder().Configuration.GetSection("ConnectionStrings")["MyConn"]);
}
base.OnConfiguring(optionsBuilder);
}
}
}
Configuring Database Context in Program.cs
Inside the Program.cs file, the DbContext service is added to the WebApplicationBuilder class.
using ConnectionString_OnConfiguration_Core_7;
var builder = WebApplication.CreateBuilder(args);
// Enabling MVC
builder.Services.AddControllersWithViews();
builder.Services.AddDbContext<DBCtx>();
var app = builder.Build();
//Configuring Routes
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside this Action method, the Top 10 records are fetched from the Customers Table of the Northwind database and returned to the View.
public class HomeController : Controller
{
private DBCtx Context { get; }
public HomeController(DBCtx _context)
{
this.Context = _context;
}
public IActionResult Index()
{
List<Customer> customers = (from customer in this.Context.Customers.Take(10)
select customer).ToList();
return View(customers);
}
}
View
Inside the View, in the very first line the Customer Entity is declared as IEnumerable which specifies that it will be available as a Collection.
For displaying the records, an HTML Table is used. A FOREACH loop will be executed over the Model which will generate the HTML Table rows with the Customer records.
@using ConnectionString_OnConfiguration_Core_7.Models;
@model IEnumerable<Customer>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<h4>Customers</h4>
<hr />
<table cellpadding="0" cellspacing="0">
<tr>
<th>CustomerID</th>
<th>ContactName</th>
<th>City</th>
<th>Country</th>
</tr>
@foreach (Customer customer in Model)
{
<tr>
<td>@customer.CustomerID</td>
<td>@customer.ContactName</td>
<td>@customer.City</td>
<td>@customer.Country</td>
</tr>
}
</table>
</body>
</html>
Screenshot
Downloads