views:

296

answers:

1

Hello, I have a list of Order objects.

These objects are shared across multiple users of my application, and change very infrequently while accessed often which makes them ideal candidates for caching.

The problem I'm facing is that I have LINQ queries against my MSSQL db which do sorting and searching - but how do I do this if I keep them in cache? I don't want to duplicate code (DRY!).

+1  A: 

In my opinion you have to do something like this

  • Have a generic method for loading the objects in memory and cache them as a list / dictionary .. whatever is suitable to you in a singleton BL class
  • Your Linq queries doing the sorting/searching have then to be done on the cached object collection in your BL class rather than directly going to your MySQL DB.

So in the case where the first call is done, your cached collection is queried, but since it is still empty, you go and fetch all objects (of course this depends on the amount of data) and then once the data is in memory, your LINQ queries are executed on it.
Subsequent calls won't hit the DB but just the cached collection.

You have to pay attention to have accesses to your collection thread-safe. Moreover you may include some refresh intervals, basically timestamps based on which you refresh your cache in some fixed intervals.

Juri