Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Be eager in the controller and call <code>.ToList()</code> before disposing in order to schedule the execution of the query immediately before you have left the <code>using</code> block (as after that it is too late, the context is gone):</p> <pre><code>using (MyEntities db = new MyEntities()) { var model = from c in db.Categories select new Category { CategoryID = c.CategoryID, Name = c.Name }; return View(model.ToList()); // &lt;-- .ToList() here } </code></pre> <p>Now, while this will solve your particular problem, what developers or dependency injection frameworks usually do is to instantiate the <code>DbContext</code> inside the <code>BeginRequest</code> event, store it inside the <code>HttpContext.Items</code> so that it is available throughout the execution of the entire request and inside the <code>EndRequest</code> method, retrieve it from <code>HttpContext</code> and dispose it.</p> <hr> <p>UPDATE:</p> <p>Also it is a good practice to use a view model containing only the properties you would like to use in this particular view:</p> <pre><code>public class CategoryViewModel { public int Id { get; set; } public string Name { get; set; } } </code></pre> <p>and then inside your action:</p> <pre><code>public ActionResult Index() { using (MyEntities db = new MyEntities()) { var model = from c in db.Categories select new CategoryViewModel { Id = c.CategoryID, Name = c.Name }; return View(model.ToList()); } } </code></pre> <p>and in the view:</p> <pre><code>@model IEnumerable&lt;MyProject.Models.CategoryViewModel&gt; @foreach (var category in Model) { &lt;p&gt; Id: @category.Id Name: @category.Name &lt;/p&gt; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload