Nhibernate Clear Cache for a Specific Region

563 Views Asked by At

I am trying to manually clear the level 2 cache for a specific region. I found the method posted in answer to this question. While this is working to clear my entities, for some reason the querycache is not getting cleared. This results in a separate query for each entity the next time the entities are retrieved from the database. If does work when I call sessionFactory.EvictQueries() without any parameters. It is only not working when I am passing in a specific region name. Any ideas as to what is going wrong?

Code is from the above link:

private void ClearRegion(string regionName)
    {
        _sessionFactory.EvictQueries(regionName);

        foreach (var collectionMetaData in _sessionFactory.GetAllCollectionMetadata().Values)
        {
            var collectionPersister = collectionMetaData as NHibernate.Persister.Collection.ICollectionPersister;
            if (collectionPersister != null)
            {
                if ((collectionPersister.Cache != null) && (collectionPersister.Cache.RegionName == regionName))
                {
                    _sessionFactory.EvictCollection(collectionPersister.Role);
                }
            }
        }

        foreach (var classMetaData in _sessionFactory.GetAllClassMetadata().Values)
        {
            var entityPersister = classMetaData as NHibernate.Persister.Entity.IEntityPersister;
            if (entityPersister != null)
            {
                if ((entityPersister.Cache != null) && (entityPersister.Cache.RegionName == regionName))
                {
                    _sessionFactory.EvictEntity(entityPersister.EntityName);
                }
            }
        }
    }

Caching is working and verified using NHProfiler.

1

There are 1 best solutions below

0
On

Ok, so I figured out my issue. I did not realize that it is necessary to specify a cache region when querying the data, aside from specifying it in the entity mapping. After adding .CacheRegion("regionName") to my queries everything works. By not adding the region when querying, it was going into the query cache without a region name. That is why it worked when I called.EvictQueries() without a region name parameter.

To sum it up, it is necessary to add the region name when mapping the entities (.Region("regionName") when using Fluent) and when querying with isession using .CacheRegion("regionName").

Thank you for you responses.