I’m using Linq to SQL and read in a blog post about closing database connections as soon as possible. As an example, they showed a variable being converted to a list (using .ToList()) instead of actually returning the Linq query. I have the below code:
public static bool HasPassword(string userId)
{
ProjDataContext db = new ProjDataContext();
bool hasPassword = (from p in db.tblSpecUser
where p.UserID == userId
select p.HasPassword).FirstOrDefault();
return hasPassword;
}
Is that query fine? Or will the database connection remain open for longer than necessary?
Thank you for any advice
The connection will be managed automatically. However, there are (or at least can be as the comments suggest) additional resouces associated with the DataContext. These resources will not be released until the DataContext is destroyed by the garbage collector. So, it is usually better to make sure that dispose is called when you don’t need the DataContext anymore.
Here it is ensured that
db.Dispose()is called when the using block exits, thus closing the connection explicitly.Edit: Following the discussion I looked at the DataContext dispose myself (also using Reflector) and found the following code (FW 3.5) which gets called from
DataContext.Dispose:So there are resources that gets freed:
DbConnection, a log (TextWriter) and aDbTransaction.CommonDataServices.LoadOptions.The provider may hold resources that needs to be disposed (
DbConnectionandDbTransaction). Also theTextWriterfor the log may have to be disposed, depending upon what instance of theTextWriterthe user has assigned to theDataContext‘s logging mechanism, e.g. a FileWriter that then gets closed automatically.The other properties hold, as far as I understand them -without looking too much into detail – only memory, but this is also made available for garbage collection by the dispose method, however, the it is not determined when the memory actually gets freed.
So, finally I totally agree with casparOne’s statement: