Reputation: 9153
I have mvc3 application and I am using EF 5 code first for data access I do get following error message, but I no nor understand why.
Can anyone explain why is this and how can I avoid the issue again?
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
My data access code is:
var list = new List<Task>();
using (var db = new SiteContext())
{
var queryableAll = db.Tasks.AsQueryable();
// setup order descending
queryableAll = (orderByTimeDescending)
? queryableAll.OrderByDescending(x => x.Created)
: queryableAll.OrderBy(x => x.Created);
list.AddRange(queryableAll
.Include("Customer")
.Include("Collection").ToList());
}
return list;
My view:
@foreach (var task in Model.Tasks.OrderByDescending(x => x.Created))
{
Html.RenderPartial("_ProjectLine", task);
}
My partial _ProjectLine
@model ProjectManagement.DataAccess.Models.Task
<tr>
<td>@Model.TaskId</td>
<td>
@Html.ActionLink(Model.Name, "ManageTask", "Task", new { id = Model.TaskId }, null)
</td>
<td>
@Model.Collection.Name
</td>
<td>@Model.Customer.Name</td>
</tr>
Update:
I get the exception when the partial view is rendering. I know if I remove using and leave it for garbage collector to dispose of, It works. But I do not like this solution.
Upvotes: 0
Views: 157
Reputation: 6383
I agree with Craig about the cause of the issue. A good way to ensure that those problem do not happen would be to create a separate, simple POCO view model class containing only information required by the view. Then you can populate it in controller, (which also gives you a hook to verify it was populated properly) and then you can pass it to view. If your view model class will not have any dependency on EF classes, there is no risk SiteContext will be still required.
Upvotes: 0
Reputation: 126547
You are disposing your context before your page renders. If you then do anything which requires an active context (e.g., referencing a lazily-loaded property, but there are many other examples -- look at the call stack in the exception to see what's setting it off for you), then you will see this error.
The usual way to avoid this is to configure your DI container to scope the context lifetime around the HTTP request and then pass the context to your method with constructor injection instead of explicitly instantiating / disposing it in a using block.
See Mark Seeman's book Dependency Injection in .NET for examples.
Upvotes: 2