MVC 4,EF 4.3的应用程序请求的生命周期中的环境管理 [英] MVC 4, EF 4.3 Managing context during the lifecycle of an Application Request

查看:201
本文介绍了MVC 4,EF 4.3的应用程序请求的生命周期中的环境管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

情况:我想要做的就是访问一个页面的生命周期的数据上下文。这主要是为了(一)避免使用系列()和避免的(B)出时延迟加载的属性被访问视图范围的异常。

Situation: What I'd like to do is have access to the data context for the life cycle of a page. This is primarily to (a) avoid series of using() and to avoid (b) out of scope exceptions in the view when a lazy loaded property is accessed.

编辑:我使用MVC 4和Entity Framework 4.3.1(最新的)

I'm using MVC 4 and Entity Framework 4.3.1 (the latest)

我通常做的是

using (MyDB b = new MyDB()) {
 ...do all my stuff
}

在我的控制器或数据层。关于这个的好处,根据我的阅读,它是干净的,不会造成内存泄漏等,但缺点是,即使单个页面的生命周期我最后一次这样了,我的对象在失去上下文查看我已经放置在上下文的。

In my controller or the data layer. The nice thing about this, based on my reading, is it's clean, causes no memory leaks etc. But the disadvantage is that even for the lifecycle of a single page I end up doing this again and again, and my objects lose context in the view as I've already disposed of the context.

我做了一些阅读和发现了一个类似的职位从2009年,但在答案没有code。当然,一些人已经找到了如何解决这个 - 我想我必须做的东西

I did some reading and found a similar post from 2009 but with no code in the answer. Surely some others have figured out how to solve this - I figure I have to do something with

Application_BeginRequest and EndRequest

但我只是不知道如何,什么陷阱/最佳做法。

But I'm just not sure how, and what the gotchas/best practices are.

感谢您的帮助(有一些code样品如果可能的话!)

Thank you for your help (with some code sample if possible!)

推荐答案

我看你有asp.net MVC的标签,所以我认为这是你所使用的。

I see you have a tag for asp.net MVC so I assume that is what you're using.

您应该实现像库的办法<一href=\"http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application\" rel=\"nofollow\">http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

不管怎么说,你真正需要做的就是这样的事情在每个控制器

Anyways, all you really need to do is something like this on each of your controllers

private MyDB b = null;
public MyController()
{
      b = new MyDB();
}

protected override void Dispose(bool disposing)
{
      b.Dispose();
      base.Dispose(disposing);
}

这篇关于MVC 4,EF 4.3的应用程序请求的生命周期中的环境管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆