申报的DbContext - 框架4.1 - 3.0 MVC [英] DbContext declaration - Framework 4.1 - MVC 3.0

查看:122
本文介绍了申报的DbContext - 框架4.1 - 3.0 MVC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

它是正确的控制器申报的DbContext一个全局变量,然后用它所有数据库操作?

Is it correct to declare a global variable of "DBContext" in a controller and then use it for all database operations?

例如:

public class ProductController : Controller
{
    private readonly DBContextEntities _db = new DBContextEntities();

    public ActionResult Index()
    {
     var products = _db.Products.ToList();
     return View(products);
    }

    public ActionResult Create()
    {
     _db.Products.AddObject(new Product{Name="x",Price="5.2"});
     _db.SaveChanges();
     return View(products);
    }

}

请咨询,

推荐答案

我试图权衡这件事几次。我得出的结论,这是应当在大部分情况下是好的。这就是为什么我觉得应该没问题。

I have tried to weigh this up a few times. I've come to the conclusion that it is should be ok in the majority of situations. This is 'why' I think it should be ok.

所有的意见建议保持上下文开放尽可能少的时间越好,这是为了避免被加载并保持在内存吨实体。
这将导致你认为应该在上下文中创建并放置在每一个方法,而不是在全球范围内的一类。

All the advice suggests keeping the context open for as little time as possible, this is to avoid tons of entities being loaded and held in memory. This would lead you to thinking that the context should be created and disposed in each method, rather than globally in a class.

由于HTTP请求的持续时间是小的,具有全球可用的上下文不应该是一个重大的开销,来创建上下文每次将超过保持其开放,所述请求的持续时间的好处所需的资源。

Since the duration of an HTTP request is small, having the context available globally shouldn't be a major overhead, the resources needed to create the context each time would outweigh the benefits of keeping it open for the duration of the request.

这个答案是从web表单的角度来看,我不是100%,如果一个MVC控制器会比要求再维持生命,并需要不同的反应我很害怕。

This answer is from a webforms perspective, I'm not 100% if an MVC controller would be kept alive for longer than a request and require a different response I'm afraid.

我觉得关键是不要设置上下文为任何静态的,或者说这是为了生活应用程序的时间,因为这将引领你进入海量内存消耗内存的实体数量的增长。

I think the key is not to set the context as anything static, or something which is intended to live for the duration of the application, as this will lead you into massive memory consumption as the number of entities in memory grows.

您可能会说,没有明确把东西实现IDisposable using块里面是一个坏主意,这我同意。

You could argue that not explicitly putting something which implements IDisposable inside a using block is a bad idea, which I'd agree with.

(免责声明:猜测款!)
这是我不能确定的资源的可能性保持打开,如果页面吸盘异常或相似。我认为99.9%的时间你会被罚款,但是当资源没有正确处置可能会有极少数情况下

(disclaimer: guesswork paragraph!) This is where I'm unsure of the possibility of resources being left open if the page chucks an exception or similar. I think 99.9% of the time you'd be fine, but there may be rare cases when the resource isn't disposed of correctly

这篇关于申报的DbContext - 框架4.1 - 3.0 MVC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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