Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the database context in a controller

I am trying all day to figure out to get the ApplicationDbContext in the ManageController.cs of a default MVC 6 project.

I went online and Googled a lot but no one seems to have the same problem as I have with it. It is probably simple but I can't figure it out. Anyone has an idea?

Here is what I tried:

IServiceProvider service = new IServiceProvider();
var _context = service.GetService<ApplicationDbContext>();
like image 674
StuiterSlurf Avatar asked Aug 20 '16 15:08

StuiterSlurf


People also ask

What is database context?

A DbContext instance represents a session with the database and can be used to query and save instances of your entities. DbContext is a combination of the Unit Of Work and Repository patterns. Entity Framework Core does not support multiple parallel operations being run on the same DbContext instance.

What is controller context?

ControllerContext(HttpContextBase, RouteData, ControllerBase) Initializes a new instance of the ControllerContext class by using the specified HTTP context, URL route data, and controller.


1 Answers

Use constructor injection:

public class ManageController
{
    private readonly ApplicationDbContext _context;

    public ManageController(ApplicationDbContext context)
    {
        _context = context;
    }
}

Then you can use the _context object in your controller methods. There's more info in the Dependency Injection section of the docs.

like image 57
Nate Barbettini Avatar answered Sep 18 '22 13:09

Nate Barbettini