Note that there are some explanatory texts on larger screens.

plurals
  1. POMVC 3 - The ObjectContext instance has been disposed and can no longer be used for operations that require a connection
    primarykey
    data
    text
    <p>I'm very new to C# and MVC in general and I've been creating my own little blog site as a test project. Although most things are working up to this point, I have had problems selecting multiple columns from LINQ queries. It was only after stumbling on a question on SO that I realised I could use the generated entities classes as strongly-typed models to handle this. I've needed this as I've been creating a database layer (which is also something I've not used before) and trying to pass anonymous types through that layer didn't work. I understand why that was the case, so I'm satisfied that I'm heading in the right direction.</p> <p>However, this approach seems to have given me another problem. I've tried a simple test to retrieve 2 columns from my Categories table: CategoryID and Name. I initially tried the following:</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); } </code></pre> <p>This gave me the ObjectContext is disposed error when trying to iterate over the model in the view. After reading <a href="https://stackoverflow.com/questions/2884332">this question</a>, I tried moving the return statement outside of the using block and calling AsEnumerable() on the model like so:</p> <pre><code>IEnumerable&lt;Category&gt; model; using (MyEntities db = new MyEntities()) { model = from c in db.Categories select new Category { CategoryID = c.CategoryID, Name = c.Name }; } return View(model.AsEnumerable()); </code></pre> <p>However, this is still giving me the same ObjectContext is disposed error when I try to iterate over the model in the view. So now I don't understand why I'm getting the error. I've even tried removing the using directive completely but that gives me a different error:</p> <p>"The entity or complex type 'MyProjectModel.Category' cannot be constructed in a LINQ to Entities query."</p> <p>If it helps, here's the relevant code for my view:</p> <pre><code>@model IEnumerable&lt;MyProject.Models.Category&gt; @foreach (var category in Model) { &lt;p&gt;@category.Name&lt;/p&gt; } </code></pre> <p>Would someone be kind enough to enlighten me as to what I'm missing?</p> <p>Thanks.</p>
    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.
 

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