如何从Owin管道中获取ApplicationDbContext [英] How to get ApplicationDbContext out of the Owin pipeline
问题描述
这必须很简单,但是我很难找到答案.控制器动作如何获得对保存在Owin管道中的每个请求的ApplicationDbContext的引用?
This has to be simple, but I'm going bug-eyed trying to find the answer. How does a controller action get a reference to the per-request ApplicationDbContext that was stashed in the Owin pipeline?
好的,我想我越来越近了……也许不是……我所有的谷歌搜索似乎都导致了
Ok, I think I'm getting closer... or maybe not... All of my Googling seems to lead to this blog post, which sez to use:
var dbContext = context.Get<ApplicationDbContext>();
其中上下文显然是Microsoft.Owin.IOwinContext
的实例.所以我尝试了:
where context is apparently an instance of Microsoft.Owin.IOwinContext
. So I tried:
var db = HttpContext.GetOwinContext().Get<ApplicationDbContext>();
但是Get<T>
方法需要一个string key
参数. :(
But the Get<T>
method requires a string key
parameter. :(
推荐答案
答案(显然)是... 您需要添加using语句才能使其正常工作:
And the answer (apparently) is... You need to add this using statement to get it to work:
using Microsoft.AspNet.Identity.Owin;
因此,完整的示例如下:
so a complete example would look like:
using Microsoft.AspNet.Identity.Owin;
public class HomeController : Controller
{
public ActionResult Index()
{
var context = HttpContext.GetOwinContext().Get<ApplicationDbContext>();
DoSomething(context); // Use the context object; do not dispose it!
return View();
}
}
这篇关于如何从Owin管道中获取ApplicationDbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!