DbContext declaration - Framework 4.1 - MVC 3.0

别说谁变了你拦得住时间么 提交于 2019-12-25 04:06:59

问题


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

Example:

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);
    }

}

Please Advice,


回答1:


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.

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.

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.

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

(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



来源:https://stackoverflow.com/questions/10534464/dbcontext-declaration-framework-4-1-mvc-3-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!