I’m making an ASP.NET MVC project and i would like to implement business data caching at repository (LINQ2SQL) layer. Since entities are related to each other, i need to invalidate related ones when i’m invalidating some base entity. Say i have Blog/Post/Comments relation and when user makes a new comment then i need to invalidate cached Post entity since it has outdated TotalComments field. Sometimes there is as more complicated logic for invalidation other entities.
Well, i need to implement flexible invalidation mechanism for that purpose. What i’ve found before:
– SQL notifications service. It notifies the app each time table has changed. Since i’ll have high-loaded application, changes on some tables gonna be very often. All cached comments to any post will drop each time a new comment is added.
– Caching LINQ(or SQL) queries. In this case the rendered query is placed to the cache using its hash as a key. Not bad but it will be impossible to drop “all comment entities having BlogPostId = deletedBlogPostId”
And now what my idea is. I wanna use LINQ queries over HttpRuntime.Cache items to find items to be deleted by their properties (e.g. in case of deleting a blog post i look for
cachedItem => cachedItem.GetType() == typeof(Comment)
&& ((Comment)cachedItem).BlogPostId == deletedBlogPostId
to delete all related comments). But i can’t find in google this approach is widely used. Isn’t it a good way to manipulate with cached related entities? Query performance over 1M cached items is 600 ms on my notebook.
Thanks!
I would just call a cache clearing method in your controller for the corresponding object. As an example, if a user is editing an individual post, then in the controller method that handles that POST request you should clear the cache for that post.
Using SQL Server Notification Services seems backwards to me. Your server-side web application is the first point of entry for users; the database comes after. You know when you need to clear the cache in your MVC application, so why not clear the cache from there?
Edit:
One other option for storing your data in cache and having access to it via key (so you don’t have to iterate over the entire cache collection):
Where value is a
List<Comment>andpostIdis the id of your post. This way you could easily look up your comment collection and your cache keys are dynamic. I’ve used this approach across many applications (though I would actually write it to be more generic for less code duplication).