Asked by:
Can't instantiate a DbContext in a Controller

Question
-
User-1370514677 posted
Hi everyone,
I'm trying to instantiate a DbContext inside my controller to create a new article in the DB :
using System; using Microsoft.AspNetCore.Mvc; using Test.Contexts; namespace Test.Controllers { public class ArticleController : Controller { [HttpGet] public IActionResult Create() { return View(); } [HttpPost] public IActionResult SaveArticleToDB() { try { var db = new TestContext(); db.Add(new Article{Title=Request.Form["Title"],Content=Request.Form["Content"]}); db.SaveChanges(); } catch(Exception e) { Console.WriteLine("ERROR : Failed to save article to DB\n" + e); } return Redirect("/"); } } }
Here is Test.Contexts (TestContext.cs) :
using Microsoft.EntityFrameworkCore; using Test.Models; namespace Test.Contexts { public class TestContext : DbContext { public TestContext(DbContextOptions<TestContext> options) : base(options) {} public DbSet<Article> Article { get; set; } } }
I always get error CS7036 : There is no argument given that corresponds to the required formal parameter of 'options'.
Thank you in advance for your help.
Tuesday, November 17, 2020 1:08 PM
All replies
-
User-474980206 posted
C# beginners 101. If a class constructor requires a parameter, it must be supplied. You dbcontext requires an options parameter when calling the constructor
var db = new TestContext(new DbContextOptions<TestContext> { // set option values here });
Use should also add a using statement to dispose the context. It more common practice to use DI for a dbcontext
Tuesday, November 17, 2020 3:37 PM -
User-1370514677 posted
Hi @bruce ! Thank you for your answer.
But I get an exception :
ERROR : Failed to save article to DB
System.InvalidOperationException: No database provider has been configured for this DbContext.The issue is that I've already configured my DbContext as service in Startup.cs :
public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddDbContext<TestContext>(options => options.UseSqlite(Configuration.GetConnectionString("TestContext"))); }
And added the followin in appsettings.json :
"ConnectionStrings":{ "TestContext": "Data Source=test.db" }
Tuesday, November 17, 2020 3:59 PM -
User475983607 posted
Core uses Dependency Injection. Passing the DbContext is covered in every beginning level tutorial and openly published in the fundamental documentation.
https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/?view=aspnetcore-5.0
public class MoviesController : Controller { private readonly MvcMovieContext _context; public MoviesController(MvcMovieContext context) { _context = context; } // GET: Movies public async Task<IActionResult> Index() { return View(await _context.Movie.ToListAsync()); }
public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddDbContext<MvcMovieContext>(options => options.UseSqlServer(Configuration.GetConnectionString("MvcMovieContext")));
Tuesday, November 17, 2020 4:07 PM -
User1120430333 posted
You need to be reading DBcontext 101 and know what you are doing if trying to make your own Dbcontext. How can you be using the 'new' keyword to instance a Dbcontext when you have setup to dependency inject the connectionstring in startup.cs using 'option'?
How does dependency injection come into play that you seem to be missing?
https://docs.microsoft.com/en-us/ef/core/dbcontext-configuration/
Tuesday, November 17, 2020 9:40 PM