Reputation: 525
I want to use a constructor to set the database connection in the controller. Currently, I am using using
keyword for setting up the DB connection in each controller like below.
public class ApplicationDbContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlServer("DefaultConnection");
}
}
and the controller is
using System;
using Microsoft.AspNetCore.Mvc;
using static WebApplication1.Models.Model;
namespace WebApplication1.Controllers
{
public class BlogController : Controller
{
public IActionResult Index()
{
using (var db = new ApplicationDbContext ()) {
db.Add(new Blog { Url = "Hello! How are you" });
db.SaveChanges();
return View();
}
}
}
}
In this, I want to use the controller constructor to set the DB connectcion. something like this.
private readonly ApplicationDbContext _db;
public BlogController(ApplicationDbContext db)
{
_db = db;
}
Upvotes: 1
Views: 1268
Reputation: 247443
Configure the context during startup so that it can be injected into the controller
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer("DefaultConnection")
);
And refactor the context to expect the options in its constructor so that the options can be injected into the context as well.
public class ApplicationDbContext : DbContext {
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options): base(options) {
}
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
Upvotes: 2