LINQ to SQL and the quest for the perfect DataContext “lifetime”
Posted by: Dilip Krishnan
Reading posts like this from Microsoft MVP’s, it’s quite obvious that the best practices around using LINQ to SQL aren’t really evangalized well enough. Siting the post not because it is bad or un-insightful in any way; but just that even Microsoft MVP’s are struggling with how to wrap their heads around how the use the power of LINQ to SQL in a high transaction/availability web applications.
The problem here isnt with LINQ however, but its unfortunately named cousin, LINQ-to-SQL. As one of the commenters points out
The problem stems from the fact Microsoft have effectively merged two design patterns (Unit of work and Data gateway) into a single object - DataContext.
Well that too! The fundamental problem IMHO, is that there is coupling of two concerns namely object/change-tracking, and LINQ provider for SQL server. If it were properly factored/separated so that the facilities like change-tracking could be layered on top LINQ, then building n-tiers applications wouldn’t be the subject of so many posts on the web!! At the very least it wouldn’t be easy to create applications poorly architected for performance and scalability. The Datacontext not very different from DataSets, only packaged disguised and bundled with a LINQ provider to SQL Server.
- Datasets support change tracking
- Datasets can can manage relationships of entities within it
- Both make it easy to create database centric applications the quick and dirty way
Enough ranting! On to my opinion about what the lifetime of the DataContext should be
* For web application, Short and sweet and ignore the change tracking feature
* For a winforms application, i’d say long live DataContext!
Can really leverage object tracking and change tracking features
This comment on the same post seemed very interesting
If we have this, of course we could use what it’s called Linq to SQL “POCO Support”, this means that we are not forced to use the auto-generated classes with its EntitySets and EntityRefs, we can use just any plain class with the appropiate attribute decoration.
This allows to create your own disconnected change tracking (there’s no Microsoft solution to this problem in current versions, either in the upcoming Entity Framework)
The commenter has a project at codeplex and it seems an interesting solution



You must be logged-in to post a comment. Log-in/Register