title: On usage of DbContext in ASP.NET using EF 6.1.1
body: <p>Since I have been working on my web application with MVC framework, I have been wondering about where I should have a definition of <code>DbContext</code>. I am aware of memory leak and normally, that is in <code>ConsoleApplication</code>, I would enclosed usage of <code>DbContext</code> withing <code>using() {}</code> clause. However, Web Application seems to be different and I am pretty sure lifetime of <code>DbContext</code> is different and I cannot just dispose it a controller and then try to read from it in Views. Or maybe I am wrong here. At first, I was creating multiple references in each Action. I came with this idea to put <code>DbContext</code> definition as a <code>readonly private</code> field within each controller:</p>
  
  <pre><code>public HomeController : controller
  {
      private readonly MyDBContext myDbContext = new MyDBContext();
  
      // ... and in actions
  
      public ActionResult Index()
      {
          // ... usage of myDbContext
      }
  
      public ActionResult Create()
      {
          // ... usage of myDbContext
      }
  
      public ActionResult Edit()
      {
          // ... usage of myDbContext
      }
  
      public ActionResult Delete()
      {
          // ... usage of myDbContext
      }
  }
  </code></pre>
  
  <p>Do you think it is correct.</p>
  
  <p>Cheers!</p>
  
  <p><hr>
  EDIT:
  I changed the code to this:</p>
  
  <pre><code>public ActionResult Index()
  {
      IQueryable&lt;MyViewModel&gt; viewModel = null;
      using (MyDBContext dB = new MyDBContext())
      {
          viewModel = from st in dB.Students
                      join d in dB.Departments on st.DepartmentID equals d.DepartmentID
                      join g in dB.Genders on st.GenderID equals g.GenderID
                      select new MyViewModel
                      {
                          StudentID= st.StudentID,
                          StudentName = st.StudentName,
                          Gender = g.GenderName,
                          DepartName = d.DepartmentName
                      };
      }
      return View(viewModel);
  }
  </code></pre>
  
  <p>and exception was thrown saying: "<em><strong>The operation cannot be completed because the DbContext has been disposed</strong></em>" when I refer to <code>@Model</code> in View in the line:</p>
  
  <pre><code>@foreach (MyViewModel item in @Model) // compiler points at @Model
  </code></pre>
  
  <p>PLEASE Note that the code works otherwise, without any other changes but removing <code>using() {}</code>.</p>