Side effects of SessionFactory.Evict?

1.2k views Asked by At

Every so often I am tasked with making alterations to one or more business entities in our database that may already be cached in our internal application. To get the application to reflect these changes without cycling the app pool, I figured I'd embed the ability for dev/administrators to evict the cache from within the app's UI (either entirely or for certain objects), but I noticed the comments for the method state the following...

/// <summary>
/// Evict an entry from the process-level cache.  This method occurs outside
///     of any transaction; it performs an immediate "hard" remove, so does not respect
///     any transaction isolation semantics of the usage strategy.  Use with care.
/// </summary>
void ISessionFactory.Evict(Type persistentClass, object id);

What exactly does that mean? What could go wrong if I try to evict one or more objects that may be involved in a transaction, and is there anyway to avoid these side effects if they are destructive? I'm currently using SysCache2 and am looking for implementation details on how to use SqlDependency but I'm still curious about the Evict effects in the mean time.

UPDATE: Upon looking closer at the comments, it appears that SessionFactory.Evict() and SessionFactory.EvictCollection() remove from the process level cache, and SessionFactory.EvictEntity() remove from the second level cache. However the same disclaimer exists on either flavor. So my original question still stands. What dangers are there of evicting an entity from the cache (process or second level) if it's currently in use in another transaction?

1

There are 1 answers

3
Jugal Panchal On

Evict detaches the entity from session.

private static Book CreateAndSaveBook(ISessionFactory sessionFactory)
{
    var book = new Book()
    {
        Name = "Book1",
    };

  using (var session = sessionFactory.OpenSession())
  {
    using (var tx = session.BeginTransaction())
    {
         session.Save(book);
         tx.Commit();
         session.Evict(book);
    }
  }
 return book;
}

In CreateAndSaveBook, we create a book and save it to the database. We commit our transaction, evict the book from session, close the session, and return the book. This sets up our problem. We now have an entity without a session. Changes to this entity are not being tracked. It's just a plain ordinary book object.

We continue to change the book object, and now we want to save those changes. NHibernate doesn't know what we've done to this book. It could have been passed through other layers or tiers of a large application. We don't know with which session it's associated, if any. We may not even know if the book exists in the database.