Remove deleted items from first level cache in NHibernate? Or: how to check if cached items have been deleted?

StackOverflow https://stackoverflow.com/questions/11626635

Pergunta

We have a brownfield multi-user application (99% Delphi, 1% .net) which uses NHibernate for the persistency of the .net modules. In my application I can add categories to some entity. If I select one and decide to not use it (thus removing the category again) I has been loaded by NHibernate and will stay in the session's first level cache. Now, if some other user deletes this category and I try to save my entity my application throws an exception because the object loaded doesn't exist anymore.

my question: is there a way to check if my cache has items loaded which don't exist anymore? and if so, is there a way to remove non-exist entities from my cache?

So what happens: I load an entity (added to session cache) I add a category (added to session cache) Someone else deletes the category from the database. I save my entity and the exception occurs because the category doesn't exist anymore.

It's still in the session cache. It would be nice if I could (automatically) remove it from my session's cache? is there a way to clean up the cache and remove objects that don't exist anymore?

Regards, Ted

Foi útil?

Solução

There's no option in NHibernate to do it automatically, at least not with ISession. You could use IStatelessSession for loading, since it doesn't have first-level cache, but you'll lose many other features that ISession provides.

You could also call ISession.Clear() to clear the session (first-level) cache, or ISession.Evict() to evict certain entities from session, but that's not automatic.

How long do you keep your session object? Maybe you need a different session management context.

If the lifespan of your session is shorter, you can still achieve entity caching, but with second-level cache. SysCache2 is one of second-level cache providers that has a support for SqlCacheDependency. This means that you could set cache expiration when some objects in database change.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top