title: EF (entity framework) usage of "using" statement
body: <p>I have a project on MVC. We chose EF for our DB transactions. We created some managers for the BLL layer. I found a lot of examples, where "<code>using</code>" statement is used, i.e.</p>
  
  <pre><code>public Item GetItem(long itemId)
      {
          using (var db = new MyEntities())
          {
              return db.Items.Where(it =&gt; it.ItemId == itemId &amp;&amp; !it.IsDeleted).FirstOrDefault();
          }
      }
  </code></pre>
  
  <p>Here we create a new instance of DBcontext <code>MyEntities()</code>.
  We using "<code>using</code>" in order to <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement" rel="noreferrer">"ensure the correct use of IDisposable objects."</a></p>
  
  <p>It's only one method in my manager. But I have more than ten of them.
  Every time I call any method from the manager I'll be using "<code>using</code>" statement and  create another DBcontext in the memory. When will the garbage collector (GC) dispose them? Does anyone know?</p>
  
  <p>But there is alternative usage of the manager methods.
  We create a global variable:</p>
  
  <pre><code>private readonly MyEntities db = new MyEntities();
  </code></pre>
  
  <p>and use DBcontext in every method without "<code>using</code>" statement. And method looks like this:</p>
  
  <pre><code>public Item GetItem(long itemId)
  {
      return db.Items.Where(it =&gt; it.ItemId == itemId &amp;&amp; !it.IsDeleted).FirstOrDefault();
  }
  </code></pre>
  
  <p>Questions:</p>
  
  <ol>
  <li>What is the proper way of using DBcontext variable?</li>
  <li>What if we wouldn't use "<code>usage</code>" statement (because it affects the performance) - GC will do all for that?</li>
  </ol>
  
  <p>I'm a "rookie" in EF usage and still haven't found the unequivocal answer for this question.</p>