Update - The answer is apparently that DbLinq doesn't implement Dispose()
properly. D'oh!
The below is all sort of misleading - Bottom line: DbLinq is not (yet) equivalent to LinqToSql, as I assumed when I originally asked this question. Use it with caution!
I'm using the Repository Pattern with DbLinq. My repository objects implement IDisposable
, and the Dispose()
method does only thing--calls Dispose()
on the DataContext
. Whenever I use a repository, I wrap it in a using
block, like this:
public IEnumerable<Person> SelectPersons()
{
using (var repository = _repositorySource.GetPersonRepository())
{
return repository.GetAll(); // returns DataContext.Person as an IQueryable<Person>
}
}
This method returns an IEnumerable<Person>
, so if my understanding is correct, no querying of the database actually takes place until Enumerable<Person>
is traversed (e.g., by converting it to a list or array or by using it in a foreach
loop), as in this example:
var persons = gateway.SelectPersons();
// Dispose() is fired here
var personViewModels = (
from b in persons
select new PersonViewModel
{
Id = b.Id,
Name = b.Name,
Age = b.Age,
OrdersCount = b.Order.Count()
}).ToList(); // executes queries
In this example, Dispose()
gets called immediately after setting persons
, which is an IEnumerable<Person>
, and that's the only time it gets called.
So, three questions:
- How does this work? How can a disposed
DataContext
still query the database for results after theDataContext
has been disposed? - What does
Dispose()
actually do? - I've heard that it is not necessary (e.g., see this question) to dispose of a
DataContext
, but my impression was that it's not a bad idea. Is there any reason not to dispose of a DbLinqDataContext
?