本文介绍了如何在控制器中获取数据库上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我整天都在努力弄清楚如何在默认MVC 6项目的ManageController.cs中获得ApplicationDbContext.
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?
这是我尝试过的:
IServiceProvider service = new IServiceProvider(); var _context = service.GetService<ApplicationDbContext>();推荐答案
使用构造函数注入:
public class ManageController { private readonly ApplicationDbContext _context; public ManageController(ApplicationDbContext context) { _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.
更多推荐
如何在控制器中获取数据库上下文
发布评论