Should Entity Framework Context be Put into Using

2020-01-29 03:51发布

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?

9条回答
啃猪蹄的小仙女
2楼-- · 2020-01-29 04:31

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.

查看更多
Summer. ? 凉城
3楼-- · 2020-01-29 04:35

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
    }

1) EF with using.

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

     }

2) 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?

查看更多
smile是对你的礼貌
4楼-- · 2020-01-29 04:38

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.

查看更多
登录 后发表回答