Should Entity Framework Context be Put into Using Statement?

C#Entity Framework

C# Problem Overview


The Entity Framework context object implements a Dispose() method which "Releases the resources used by the object context". What does it do really? Could it be a bad thing to always put it into a using {} statement? I've seen it being used both with and without the using statement.

I'm specifically going to use the EF context from within a WCF service method, create the context, do some linq and return the answer.

EDIT: Seems that I'm not the only one wondering about this. Another question is what's really happening inside the Dispose() method. Some say it closes connections, and some articles says not. What's the deal?

C# Solutions


Solution 1 - C#

If you create a context, you must dispose it later. If you should use the using statement depends on the life time of the context.

  1. If you create the context in a method and use it only within this method, you should really use the using statement because it gives you the exception handling without any additional code.

  2. If you use the context for a longer period - that is the life time is not bound by the execution time of a method - you cannot use the using statement and you have to call Dispose() yourself and take care that you always call it.

What does Dispose()do for an object context?

I did not look at the code, but at least I exspect it to close the database connection with its underlying sockets or whatever resources the transport mechanism used.

Solution 2 - C#

Per Progamming Entity Framework: "You can either explicitly dispose the ObjectContext or wait for the garbage collector to do the job."

So in short, while the using statement isn't required, it's best practice if you know you're done using the ObjectContext since the resource is freed up immediately instead of waiting for garbage collection.

Solution 3 - C#

Since you don't know when the garbage collector disposes an item, it's always good to wrap up objects that implement IDisposable in a using-block if you know when you're done with it.

Solution 4 - C#

EF5 and before version

    using { ...
            // connecction open here.
    
            ...
            context.Blogs.Add(blog); 
            context.SaveChanges();   // query etc now opens and immediately closes 
                
            ...
            context.Blogs.Add(blog); 
            context.SaveChanges();   // query etc now opens and immediately closes 
   }

EF6 and after version

 using {
        // connecction open here.

        ...
        context.Blogs.Add(blog); 
        context.SaveChanges(); 

        // The underlying store connection remains open for the next operation  
            
        ...
        context.Blogs.Add(blog); 
        context.SaveChanges(); 

        // The underlying store connection is still open 

   } // The context is disposed – so now the underlying store connection is closed

Reference: http://msdn.microsoft.com/en-us/data/dn456849#open5

Solution 5 - C#

Always, if you instantiate a class that implements IDisposable, then you are responsible for calling Dispose on it. In all but one case, this means a using block.

Solution 6 - C#

When you dispose, the ObjectContext disposes other owned objects.

Including things like the EntityConnection which wraps the actual database connection, i.e. generally a SqlConnection.

So 'if' the SqlConnection is open it will be closed when you dispose the ObjectContext.

Solution 7 - C#

I realy tested this thing for both ADO.net and EF v.6 and watched connections in SQL table

select * from sys.dm_exec_connections

Methods to be tested looked like this:

  1. ADO.net with using

    using(var Connection = new SqlConnection(conString)) { using (var command = new SqlCommand(queryString, Connection)) {
    Connection.Open(); command.ExecuteNonQueryReader(); throw new Exception() // Connections were closed after unit-test had been //finished. Expected behaviour } }

  2. ADO.net withour using

    var Connection = new SqlConnection(conString); using (var command = new SqlCommand(queryString, Connection)) { Connection.Open(); command.ExecuteNonQueryReader(); throw new Exception() // Connections were NOT closed after unit-test had been finished

      finished.  I closed them manually via SQL.  Expected behaviour
     }
    
  3. EF with using.

    using (var ctx = new TestDBContext()) { ctx.Items.Add(item); ctx.SaveChanges(); throw new Exception() // Connections were closed, as expected.

      }
    
  4. EF without using

    var ctx = new TestDBContext();
    ctx.Items.Add(item); ctx.SaveChanges(); throw new Exception() // Connections WERE successfully closed, as NOT expected.

I don't know why is it so, but EF automatically closed connections. Also All the patterns of repository and UnitOfWork which use EF don't use using. It's very strange for me, because DBContext is Disposable type, but it's a fact.

Maybe in Microsoft they did something new for handling?

Solution 8 - C#

I have noticed (although in only one application) that the explicit disposal was causing thread abort exceptions in mscorlib which are caught before the application code, but at least in my case resulting in a noticeable performance hit. Haven't done any significant research on the issue, but probably something worth consideration if you are doing this. Just watch your DEBUG output to see if you are getting the same result.

Solution 9 - C#

If Dispose closes connection to DB it is a bad idea to call it. For example in ADO.NET connections are in connection pool and never be closed before timeout or application pool stop.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJohan DanforthView Question on Stackoverflow
Solution 1 - C#Daniel BrücknerView Answer on Stackoverflow
Solution 2 - C#Cory HouseView Answer on Stackoverflow
Solution 3 - C#ullmarkView Answer on Stackoverflow
Solution 4 - C#user3556898View Answer on Stackoverflow
Solution 5 - C#John SaundersView Answer on Stackoverflow
Solution 6 - C#Alex JamesView Answer on Stackoverflow
Solution 7 - C#Artem GView Answer on Stackoverflow
Solution 8 - C#Lewis TathamView Answer on Stackoverflow
Solution 9 - C#IlyaView Answer on Stackoverflow