If you query the DbSet of a DbContext, the query is valid until the DbContext is disposed. The following will lead to an exception:
IQueryable<Video> allVideos = null;
using (var context = new MyDbContext())
{
allVideos = context.Videos;
}
var firstVideo = allVideos.first();
Apparently the used DbSet is stored somewhere in the returned object that implements the IQueryable.
However, MSDN advises (Link)
When working with Web applications, use a context instance per request.
Of course I could use ToList() and return the result as a list of objects, but this is rather undesirable because I don't know the reason for the query.
Example: Suppose my database has a collection countries, which have cities, which have streets, which have houses, which have families which have persons which have names.
If someone asks for the IQueryable, then it could be that he wants to search for the name of the oldest person living on Downing Street nr 10 in London in the United Kingdom.
If I returned the sequence with a ToList(), all cities, streets, houses, persons, etc would be returned, which would be quite a waste if he only needed the name of this one person. That's the nice thing about deferred execution of Linq.
So I can't return ToList(), I have to return the IQueryable.
So what I'd like to do, is open a new DbContext, and somehow tell the query that it should use the new DbContext:
IQueryable<Video> allVideos = null;
using (var context = new MyDbContext())
{
allVideos = context.Videos;
}
// do something else
using (var context = new MyDbContext())
{
// here some code to attach the query to the new context
var firstVideo = allVideos.first();
}
How to do this?