Removing objects from NHibernate second level cache
Asked Answered
P

1

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.

Predicant answered 22/11, 2009 at 7:43 Comment(4)
I know it's probably not relevant now but note that your URI scheme is incorrect. It should be Users/[Id]/ImageDB/ShowBonniebonns
@Bonniebonns - unless the app is called ImageDb :) You're still mostly right, just have to change ImageDB to /Images or somethingOssetia
@LukeSchafer: I wrote ImageDb only because the OP uses it.Bonniebonns
@Bonniebonns - yeah, sure, was just pointing out it might be a virtual directory is all :)Ossetia
K
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
Ketcham answered 30/11, 2009 at 12:8 Comment(1)
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.Conversational

© 2022 - 2024 — McMap. All rights reserved.