We've just started using LINQ to SQL at work for our DAL & we haven't really come up with a standard for out caching model. Previously we had being using a base 'DAL' class that implemented a cache manager property that all our DAL classes inherited from, but now we don't have that. I'm wondering if anyone has come up with a 'standard' approach to caching LINQ to SQL results?
We're working in a web environment (IIS) if that makes a difference. I know this may well end up being a subjective question, but I still think the info would be valuable.
EDIT: To clarify, I'm not talking about caching an individual result, I'm after more of an architecture solution, as in how do you set up caching so that all your link methods use the same caching architecture.
I found this post, which offers an extension method as a means of caching the LINQ objects.
I've been banging my head against the wall for weaks now trying to figure out a good caching solution for Linq2SQL, an must admit that I'm really struggling to find a one-size fits all...
The repository pattern tends to limit the usefullness of Linq, since (without reimplementing IQueryable) caching must bge performed outside of Linq statement.
Moreover, deferred loading and object tracking are both big no-nos if you're going to cache your objects, which makes performing updates somewhat trickier.
Anyone who's managed to solve this problem in the wild within a highly concurrent web project, please chime in and save the world! :)
My LINQ query result cache is probably just what you're looking for.
Pete.
I understand this is perhaps a bit late answer... Non the less, you can give a try to the LinqToCache project. It hooks a SqlDepdency on an arbitrary LINQ query, if possible, and provides active cache invalidation via the server side Query Notifications. The queries must be valid queries for notifications, see Creating a Query for Notification. Most Linq-to-sql queries conform to these restrictions, as long as the tables are specified using two-part names (
dbo.Table
, not onlyTable
).It's right under your nose:
Now, just cache myResult as you would have cached your old DAL's returned data.
See the 'GetReferenceData' method in the 'ReferenceData' class in this article: http://blog.huagati.com/res/index.php/2008/06/23/application-architecture-part-2-data-access-layer-dynamic-linq/
It uses the asp.net page cache for caching data retrieved using L2S.
A quick answer: Use the Repository pattern (see Domain Driven Design by Evans) to fetch your entities. Each repository will cache the things it will hold, ideally by letting each instance of the repository access a singleton cache (each thread/request will instantiate a new repository but there can be only one cache).
The above answer works on one machine only. To be able to use this on many machines, use memcached as your caching solution. Good luck!