Should Entity Framework Context be Put into Using Statement?

前端 未结 9 1669
不思量自难忘°
不思量自难忘° 2020-11-29 23:52

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 thin

相关标签:
9条回答
  • 2020-11-30 00:13

    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.

    0 讨论(0)
  • 2020-11-30 00:15

    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.

    0 讨论(0)
  • 2020-11-30 00:16

    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?

    0 讨论(0)
提交回复
热议问题