Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

dblinq

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:

  1. How does this work? How can a disposed DataContext still query the database for results after the DataContext has been disposed?
  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 a DbLinq DataContext?
like image 810
devuxer Avatar asked May 17 '10 18:05

devuxer


1 Answers

1 How does this work? How can a disposed DataContext still query the database for results after the DataContext has been disposed?

It doesn't work. There's something you're not showing us. I'm guessing that either your repository class doesn't dispose the DataContext properly/at the right time, or that you are perfunctorily writing ToList() at the end of every query, which completely negates the query transformation and deferred execution you normally get.

Try the following code in a test app, I guarantee you that it will throw an ObjectDisposedException:

// Bad code; do not use, will throw exception.
IEnumerable<Person> people;
using (var context = new TestDataContext())
{
    people = context.Person;
}
foreach (Person p in people)
{
    Console.WriteLine(p.ID);
}

This is the simplest possible reproducible case, and it will always throw. On the other hand, if you write people = context.Person.ToList() instead, then the query results have already been enumerated inside the using block, which I'll bet is what's happening in your case.

2 What does Dispose() actually do?

Among other things, it sets a flag indicating that the DataContext is disposed, which is checked on every subsequent query and causes the DataContext to throw an ObjectDisposedException with the message Object name: 'DataContext accessed after Dispose.'.

It also closes the connection, if the DataContext opened it and left it open.

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 a LinqToSql DataContext?

It is necessary to Dispose the DataContext, as it is necessary to Dispose every other IDisposable. You could potentially leak connections if you fail to dispose the DataContext. You could also leak memory if any of the entities retrieved from the DataContext are kept alive, since the context maintains an internal identity cache for the unit-of-work pattern it implements. But even if none of this were the case, it is not your concern what the Dispose method does internally. Assume that it does something important.

IDisposable is a contract that says, "cleanup may not be automatic; you need to dispose me when you're finished." You have no guarantees of whether or not the object has its own finalizer that cleans up after you if you forget to Dispose. Implementations are subject to change, which is why it's not a good idea to rely on observed behaviour as opposed to explicit specifications.

The worst thing that can happen if you dispose an IDisposable with an empty Dispose method is that you waste a few CPU cycles. The worst thing that can happen if you fail to dispose an IDisposable with a non-trivial implementation it is that you leak resources. The choice here is obvious; if you see an IDisposable, don't forget to dispose it.

like image 99
Aaronaught Avatar answered Sep 21 '22 18:09

Aaronaught