Sunday, January 06, 2008

LINQ - DataContext.Dispose()

I'm playing around with LINQ for the moment. Actually I tried Entity Framework first, but could not get that to behave as I wanted (that is Table Per Class), so I let that rest for a while until they fix TPC support in a subsequent version and tried "plain" LINQ instead.

I can't say I'm really there yet, but one thing that bit me was that I out of old habit (or whatever) used code similar to the following:

            using (DataClassesDataContext db = new DataClassesDataContext();
return (from user in db.Users
where user.Name == name
select user).SingleOrDefault();

..and I thought that all was well. However, when testing a little bit more I got  ObjectDisposedException:s when returning

return (from user in db.Users select user).AsEnumerable();

instead of

return (from user in db.Users select user).ToList();

Turns out that even though DataContext implements IDisposable, you should not use a DataContext in a using statement or directly call .Dispose() or you'll end up with lots of brokenness.

(In addition I got all kinds of attaching and detaching issues, but I think I've sorted them now. Did I already tell you that this is my first attempt of using LINQ non-trivially?)


c_marius said...


I guess is all about defered execution concepts. The way you employ Linq is does not strike me the best, because if you read Charlie Calverts article ( execution happens, roughly said,...LATER, that is as soon as you start "looping", etc.
Hope it helps, C. Marius

ecards said...

A couple quick points here:

1) Is it actually not a problem to call Dispose on a DataContext. If it doesn't work there is something else wrong.

2) Most of the time it is not necessary to call Dispose on a DataContext.

For a more complete explanation of why this is true, please see: