I’ve written a few posts about LINQ to SQL and am generally a big fan of the technology (even with its weaknesses) since it’s very productive. After creating a custom DataContext object using the LINQ to SQL designer (or one created by hand) I always ensure that the object is wrapped in a “using” statement so that the Dispose() method is called:
using (MyDataContext context = new MyDataContext())
I had assumed that not properly disposing of the DataContext object would lead to orphan SQL connections which is of course bad and will likely lead to your DBA holding a grudge against you for life. :-)
Steven Walther recently posted on the subject of disposing of DataContext objects and provided some interesting insight into what actually happens. From what he says it sounds like the DataContext object acts much like the SqlDataAdapter class. It opens the connection right before a query is executed and closes it immediately after. I don’t want to steal Steven’s thunder so check out his post on the subject (the last part of the article talks about the consequences…or lack of consequences…of not calling Dispose()).
I haven’t had time to verify the details in Reflector yet, but given that Steven’s one of the more intelligent people I know I’m confident that the details he presents are accurate. It still feels more correct to wrap “using” statements around any object that implements IDisposable or explicitly call Dispose() in my opinion, but it’s good to know how the DataContext object works behind the scenes.