Disadvantages of using entity structure without using an operator?

There are many blocks of code here:

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

    .....

      

Can I change the methods as follows:

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

        return View();
    }
    .....

      

What are the problems with using using-statement

in EF? OR what is the best way? Also, if we use using-statement

, code blocks are generated.

Thank...

+3


source to share


2 answers


The approval approach using

is the best of the two that you suggested above. By using this approach, you can be sure to ObjectContext

close and dispose of after using it.

Using your other approach, it might be assumed that it ObjectContext

might be left open-ended, so it connects to the database. To see this in action, try building a sample application with a different approach, then profile it with EFProfiler and see the number of openingsObjectContext

rise, while the number of closures will be noticeably fewer.

I recently worked on a project that had database problems at high usage, which adopted your second pattern (you can see my question about this HERE ). Since I didn't have enough time for the project / code base was too large, I had no way to switch to the subroutine using

. Instead, I applied the following to manually force the deletion ObjectContext

in End_Request

in Global.asax (I had an instance DbContext

in a static instance of mine BusinessLayerService

:



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

      

But if you have the option from running the project: I highly recommend using the templateusing

+2


source


In the example above, there is not much of a problem using the using-statement , but it is very difficult to write unit tests for code like this when the dbContext is a local variable.



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

+5


source







All Articles