ASP.NET MVC and Entity Framework: query persistance

Question!

I'm facing the following problem: in the controller I select the data I need and store it into the ViewData;

using (Models.SkedruleEntities ctx = new Models.SkedruleEntities())
{
    ViewData["users"] = (from u in ctx.User select u);
}

In the View I try to read from the ViewData like this:

<p>
    <%foreach(User user in (IEnumerable<User>)ViewData["users"]) { %>
        <div><%=user.Name %></div>
    <%}%>
</p>

But I get a System.ObjectDisposedException error, as the ViewData seems to contain the query, not the data retrieved by the query and of course the context ctx is no more available.

Any help? Thanks



Answers
You're storing the query in the view data, not the results. So in the view you get the query back and execute it. At that moment the context is already disposed.

The solution is to execute the query in the controller and store the result in the ViewData:

ViewData["users"] = (from u in ctx.User select u).ToList();


Just add ToList():

ViewData["users"] = (from u in ctx.User select u).ToList();
By : eu-ge-ne


This video can help you solving your question :)
By: admin