Posted by: Dilipkrishnan
Development, LINQ, WCF, Web services
While creating a windows application using LINQ the first thing that struck me was, yes, this is cool and it makes it looks so easy. This is great for a client-server application! After the initial eye-candy-effect faded I was stuck with a very fundamental question; what is the typical lifetime of the DataContext derived object? Are there any best practices around it? After a little bit of googling heres what I found in the LINQ Project General forum
…As you may notice, DataContext pins entity objects. hiding them from GC. That means, once object was retrieved using DataContext, it’ll be in cache until DataContext is alive. Doesn’t this mean that DataContext has to be short-lived object? Any guidelines/examples of proper using of DataContext would be really appreciated.
And the moderator’s reply
2) Yes, the DataContext should not be long-lived for a server app. You should create one to cover the duration of a transaction. For client code this is less critical.
Which leads me to think that it is not very easy to scale the application with this approach when you apply SOA and split the application into n-tiers; handy as it may be for a connection oriented applications (read: windows application), over HTTP, a protocol thats inherently disconnected, the LINQ-to-SQL model degenerates into a nifty way to query the database without using a third party ORM/ORM-like solution.
Digging further I found a couple of articles that allow you to work around this limitation either by allowing you to “Detach” and “Re-Attach” entities or working around it when they cross tier boundaries. All of these solutions mean that the DataContext has to stay around in memory to track changes and if objects created by it. If the objects are “pinned”, as the forum post suggests, this would mean web applications/services that have session affinity with a potentially large memory footprint which may not really allow the application scale!
I havent looked at what Entity framework has to offer yet, but LINQ to SQL seems very Dataset-like! Disappointing!