title: Entity Framework and calling context.dispose()
body: <p>When should one call <code>DbContext.dispose()</code> with entity framework?</p>
  
  <ol>
  <li><p><strong>Is this imaginary method bad?</strong> </p>
  
  <pre><code>public static string GetName(string userId)
  {
      var context = new DomainDbContext();
      var userName = context.UserNameItems.FirstOrDefault(x =&gt; x.UserId == userId);
      context.Dispose();
      return userName;
  }
  </code></pre></li>
  <li><p><strong>Is this better?</strong></p>
  
  <pre><code>public static string GetName(string userId)
  {
      string userName;
      using(var context = new DomainDbContext()) {
          userName = context.UserNameItems.FirstOrDefault(x =&gt; x.UserId == userId);
          context.Dispose();
      }
      return userName;
  }
  </code></pre></li>
  <li><p><strong>Is this even better, that is, should one NOT call context.Dispose() when using using()?</strong></p>
  
  <pre><code>public static string GetName(string userId)
  {
      string userName;
      using(var context = new DomainDbContext()) {
          userName = context.UserNameItems.FirstOrDefault(x =&gt; x.UserId == userId);
      }
      return userName;
  }
  </code></pre></li>
  </ol>