25

I wish to clear the entire second level cache in NHibernate via code. Is there a way to do this which is independent of the cache provider being used? (we have customers using both memcache and syscache within the same application).

We wish to clear the entire cache because of changes external to the database may have occurred (and we have no guarantees re: which tables/entities were affected, so we have to assume the worst).

Bittercoder
  • 11,753
  • 10
  • 58
  • 76

1 Answers1

36

This should do:

sessionFactory.EvictQueries();
foreach (var collectionMetadata in sessionFactory.GetAllCollectionMetadata())
         sessionFactory.EvictCollection(collectionMetadata.Key);
foreach (var classMetadata in sessionFactory.GetAllClassMetadata())
         sessionFactory.EvictEntity(classMetadata.Key);
Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154
  • Does this still work in recent (eg. 3.3.x) releases of NHibernate? – DanP May 13 '13 at 14:07
  • 1
    @DanP it should. There weren't any major changes to metadata or caching. – Diego Mijelshon May 13 '13 at 14:08
  • are there any negative repercussions to clearing this in a multi-user environment? E.g., will this cause web requests to throw a 500 if prior query results are dumped halfway through the logic? – ps2goat Nov 21 '14 at 16:19
  • @ps2goat it shouldn't. It's just a cache. – Diego Mijelshon Nov 21 '14 at 16:22
  • 1
    The important question I think ps2goat is getting at is whether the cache is thread safe. Will clearing the cache in the middle of another call reading from the cache cause any problems? – mikeschuld Jul 08 '15 at 17:02
  • It wouldn't be, but that doesn't mean everyone wrote their third party caches correctly. Just pointing out what it seemed like ps2goat actually meant with their question. – mikeschuld Jul 09 '15 at 19:37