如何在控制器中获取数据库上下文

编程入门 行业动态 更新时间:2024-10-26 11:16:38
本文介绍了如何在控制器中获取数据库上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我整天都在努力弄清楚如何在默认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.

更多推荐

如何在控制器中获取数据库上下文

本文发布于:2023-10-26 11:46:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1530041.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:上下文   器中   数据库   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!