Reputation: 1140
So I have this little problem with a query I have to return a list of items. Here is the query:
geographic = _iRepository.Geographics.Where(p => p.GeographID == ID)
.SingleOrDefault()
.Children
.SingleOrDefault()
.Children
.OrderBy(p => p.DisplayOrder).ThenBy(p => p.Name)
.ToList();
ID (as well as GeographID) are both guids. The problem is that my query gets stuck at the == part, meaning, it never finds a match. If I set a breakpoint at this part of the code, after it exits, it gives me the following error:
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection
which is weird since I had the exact same piece of code somewhere else and it worked perfectly! I should add I am using MVC 4 with Entity Framework and this is a Web Api controller (or is derived from Web Api). I have researched and heard that I could do Lazy Loading
but I'm not sure how that works.
I appreciate any and all help!
Upvotes: 1
Views: 76
Reputation: 1140
For some reason the above query didn't work and everything else I tried worked the same way (object getting disposed). So I decided to use the query appended. It is not a "solution" but it does get the job done. Thanks for all the help:
geographic = (from g1 in _iEMARepository.Geographics
join g2 in _iEMARepository.Geographics
on g1.GeographID equals g2.ParentId
join g3 in _iEMARepository.Geographics
on g2.GeographID equals g3.ParentId
where g1.GeographID == ID
select g3).OrderBy(p => p.DisplayOrder).ThenBy(p => p.Name).ToList();
Upvotes: 0
Reputation: 18977
The error says that you have disposed the DbContext object. inspect your controller code.
Maybe it's cause of creating the controller using scaffolding. If so, inspect the controller code to find somthing like the following:
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
Either remove it(not recommended) or put call your DbContext object before it.
Or maybe you dispose your object manually, or declaring your object by a using()
clause, etc. Anyway, this error occurs because you call the object after disposing it. Inspect your code...
Update:
Another guess: It seems that you are using navigation properties in the query. If so, in this case, you should include any NavPr you need. Try something like this:
geographic = _iRepository.Geographics.Include("NavPr1")
.Include("NavPr2").Include("NavPr2.NavPr21")
.Where(p => p.GeographID == ID)
.SingleOrDefault()
// and the rest of query...
Upvotes: 1