session.Merge
is perhaps one of the most misunderstood features in NHibernate. In this recipe, I'll show you how to use session.Merge
to associate a dirty, detached entity with a new session. This is particularly handy when recovering from StaleObjectStateException
s.
Using our Eg.Core
model from Chapter 1 and the Configuring NHibernate with App.config recipe from Chapter 2, set up a console application.
Add the following code to your
Main
method:var book = CreateAndSaveBook(sessionFactory); book.Name = "Dormice in Action"; book.Description = "Hibernation of the Hazel Dormouse"; book.UnitPrice = 0.83M; book.ISBN = "0123"; using (var session = sessionFactory.OpenSession()) { using (var tx = session.BeginTransaction()) { var mergedBook = (Book) session.Merge(book); tx.Commit(); // Returns false ReferenceEquals(book, mergedBook); } }
Add the
CreateAndSaveBook
method:private static Book CreateAndSaveBook( ISessionFactory...