简体   繁体   中英

Drawbacks with using entity framework without using statement?

There a lot of code blocks like this:

public class SomeController : Controller
{
    DbEntities entity = new DbEntities();

    public ActionResult Add()
    {
        entity.someOperations...
        return View();
    }

    public ActionResult Edit()
    {
        entity.someOperations...
        return View();
    }

    public ActionResult Detail()
    {
        entity.someOperations...
        return View();
    }

    public ActionResult Detail()
    {
        entity.someOperations...
        return View();
    }

    .....

Should I change the methods like this?:

public class SomeController : Controller
{
    public ActionResult Add()
    {
        using(DbEntities entity = new DbEntities())
        {
            entity.someOperations...
        }

        return View();
    }
    .....

What are the problems with not using using-statement in EF? OR what is the best way? Also, If we use using-statement code blocks are grown.

Thanks...

There's no big problem in your example above if using using-statement but it's very hard to write unit tests for code like that, when dbContext is a local variable.

If you don't follow any design pattern like Repository, Unit of Work, you don't want to write unit test, then wrap all logic in using statement is the best choice in this case.

The using statement approach is the best of the two that you have proposed above. Using this approach, you can be assured that the ObjectContext is closed and disposed of after it's use.

Using your other approach, one would assume that the ObjectContext could be left unclosed, therefore hogging connections to the database. To see this in action, try creating a sample app with your other approach, then profile it using the EFProfiler and watch the number of ObjectContext 's opened rise, whilst the number of closures will be notably smaller.

I recently worked on a project that was having database issues under high levels of usage that adopted your second pattern (you can see my question about it HERE ). As I didn't have enough time on the project/code base was too large, I didn't have the option to switch to the using statement approach. Instead I implemented the following to manually force the disposal of the ObjectContext on the End_Request in Global.asax (I had an instance of the DbContext on a static instance of my BusinessLayerService :

protected void Application_EndRequest(object sender, EventArgs e)
    {
        BusinessLayerService.Instance.Dispose();
        BusinessLayerService.Instance = null;
    }

But if you have the option from the project start: I would highly recommend using the using pattern

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM