StuiterSlurf
StuiterSlurf

Reputation: 2572

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>();

Upvotes: 14

Views: 18837

Answers (3)

5andr0
5andr0

Reputation: 2056

DbContext is not threadsafe, so if you have multiple actions in a controller class you risk concurrency proplems. You can inject a scoped DbContext into each controller action like this:

public async Task<IActionResult> Get([FromServices] ApplicationDbContext dbContext)

Or you inject a DbContextFactory into the controller class and create a new instance inside the actions with dbContextFactory.Create()

Or inject IServiceProvider services into the controller class and call

services.GetRequiredService<ApplicationDbContext>()

Upvotes: 0

Display Name
Display Name

Reputation: 15091

I am using Visual Studio 2015 Update 3. Some of the following steps might not be needed in the future release of Visual Studio.

  1. Create ASP.NET Core (with .NET Core) project with No Authentification.

  2. In Package Manager Console, execute each of the following, one after the other.

 Install-Package Microsoft.EntityFrameworkCore.SqlServer
 Install-Package Microsoft.EntityFrameworkCore.Tools –Pre
 Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Tools -Pre
 Install-Package Microsoft.VisualStudio.Web.CodeGenerators.Mvc -Pre
  1. Add the following to the "tools":{} defined in project.json.
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
"Microsoft.VisualStudio.Web.CodeGeneration.Tools": "1.0.0-preview2-final",
  1. Add the following to appsettings.json.

"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=YourDatabaseName;Trusted_Connection=True;MultipleActiveResultSets=true"
},
  1. Add the following to ConfigureServices in startup.cs right before services.AddMvc();.
string connection = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<YourContextName>(options => options.UseSqlServer(connection));

Upvotes: 0

Nate Barbettini
Nate Barbettini

Reputation: 53600

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.

Upvotes: 16

Related Questions