How to get the database context in the controller

I have been trying all day to figure out to get the ApplicationDbContext in the ManageController.cs MVC project by default.

I went online and googled a lot, but I don't have the same problem as I have with her. It is probably simple, but I can not understand it. Does anyone have an idea?

Here is what I tried:

 IServiceProvider service = new IServiceProvider(); var _context = service.GetService<ApplicationDbContext>(); 
+5
source share
2 answers

Use constructor injection:

 public class ManageController { private readonly ApplicationDbContext _context; public ManageController(ApplicationDbContext context) { _context = context; } } 

You can then use the _context object in your controller methods. There is more information in the Dependency Injection section in the docs.

+7
source

I am using Visual Studio 2015 3 update. Some of the following steps may not be needed in a future version of Visual Studio.

  • Create an ASP.NET Core project (with .NET Core) using No Authentification .

  • In the Package Manager console, do one of the following, one after the other.

  Install-Package Microsoft.EntityFrameworkCore.SqlServer Install-Package Microsoft.EntityFrameworkCore.ToolsPre Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Tools -Pre Install-Package Microsoft.VisualStudio.Web.CodeGenerators.Mvc -Pre 
  1. Add the following to "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 up to ConfigureServices in startup.cs to services.AddMvc(); .
 string connection = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContext<YourContextName>(options => options.UseSqlServer(connection)); 
0
source

All Articles