views:

548

answers:

1

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.

+4  A: 

the sessionFactory provides the methods you want... from the 17.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
Jaguar
Poor kittens...
Arnis L.