Why is it possible to enumerate a LinqToSql query after calling Dispose() on the DataContext?

Posted by DanM on Stack Overflow See other posts from Stack Overflow or by DanM
Published on 2010-05-17T18:38:27Z Indexed on 2010/05/17 18:40 UTC
Read the original article Hit count: 165

Filed under:
|
|

I'm using the Repository Pattern with some LinqToSql objects. My repository objects all 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 person, like this:

public IEnumerable<Person> SelectPersons()
{
    using (var repository = _repositorySource.GetNew<Person>(dc => dc.Person))
    {
        return repository.GetAll();
    }
}

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, a couple questions:

  1. How does this work? How can a disposed DataContext still query the database for results when I walk the IEnumerable<Person>?
  2. What does Dispose() actually do?
  3. 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 it?

© Stack Overflow or respective owner

Related posts about LINQ

Related posts about linq-to-sql