25

I just started thinking about using the NHibernate second level cache in one of my apps. I would probably use the NHibernate.Caches.SysCache.SysCacheProvider which relies on ASP.net cache.

Enabling the cache was not a problem, but I am wondering on how to manage the cache e. g. programmatically removing certain entities from the cache etc.

My application is some kind of image database. The user uploads images over a backend and can view it in the frontend by accessing /ImageDb/Show?userId=someUserId

The data does not change very often. And if it changes, the users would not matter a button named "clear my cache" in the backend that removes the cached objects for this user from the cache.

I found a solution online that can remove all cached objects from nhibernates second level cache. But thats a bit too brute force for me ... I dont want to clear the whole cache for dozens of users just because one user tried to clear the cache for his own data.

So what I basically wanted to do: selectively remove cached db objects from nhibernates second level cache in C#.

Is this possible? I guess it also depends on the cache provider. If this is not doable with the ASP.net cache provider, I am open for other built in / open source suggestions.

Jonathan Rauch
  • 693
  • 1
  • 8
  • 18
Max
  • 15,693
  • 14
  • 81
  • 131

1 Answers1

47

the sessionFactory provides the methods you want... from the 19.3 chapter of the NHibernate reference:

To completely evict all objects from the session cache, call ISession.Clear() For the second-level cache, there are methods defined on ISessionFactory for evicting the cached state of an instance, entire class, collection instance or entire collection role.

sessionFactory.Evict(typeof(Cat), catId); //evict a particular Cat
sessionFactory.Evict(typeof(Cat)); //evict all Cats
sessionFactory.EvictCollection("Eg.Cat.Kittens", catId); //evict a particular collection of kittens
sessionFactory.EvictCollection("Eg.Cat.Kittens"); //evict all kitten collections
Frédéric
  • 9,364
  • 3
  • 62
  • 112
Jaguar
  • 5,929
  • 34
  • 48
  • 6
    The role name here in the first parameter is the full Namespace+Classname+Propertyname of what you need to evict. You can see everything in cache by calling sessionFactory.GetAllCollectionMetaData().Keys. – Emil Lerch Jun 18 '11 at 14:39