Search code examples
.netnhibernatefluent-nhibernate

NHibernate handling external database update


We have two C# projects, one is a web application and the other one is a console one. Both use NHibernate+Fluent to do any database manipulations. Both applications run on the same machine.

However, we are noticing that when a console app does a database update, those same objects within the web app become stale and what is more concerning, updating them within the web app and then saving them saves the stale object back to the DB, losing the update from the console app.

Is there a mechanism or a setting to prevent such behaviour without having to call the .Refresh method on each object every time we use/refer to one?


Solution

  • Yes you can use versioned entities but in the case of saving a stale entity it will merely throw an exception telling you are trying to save a stale entity. You would need to handle this.

    Nhibernate documentation on the version column: http://nhibernate.info/doc/nhibernate-reference/mapping.html#mapping-declaration-version

    There are several stack overflow posts about this as well: When to use Nhibernate <version>? How do you do Versioning in Nhibernate?

    https://ayende.com/blog/3946/nhibernate-mapping-concurrency

    Edit

    If you don't want to change the way you are handling your sessions there are a couple things you can do.

    Call ISession.Clear() at some point to clear everything in session out so that subsequent calls to ISession.Get will return objects from the database and not cache.

    Call ISession.Evict() for a specific entity instance. This will remove the entity from cache and subsequent calls will return objects from the database and not cache.

    https://github.com/nhibernate/nhibernate-core/blob/master/src/NHibernate/ISession.cs