Using session.Merge
Session.Merge
is perhaps one of the most misunderstood features in NHibernate. In this recipe, we'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.
Getting ready
Follow the Getting ready step in the Save entities to the database recipe in this chapter.
How to do it…
Add a new folder named
MergingEntities
to theSessionRecipes
project.Add a class named
Recipe
to the folder:using System; using NH4CookbookHelpers.Queries; using NH4CookbookHelpers.Queries.Model; using NHibernate; namespace SessionRecipes.MergingEntities { public class Recipe : QueryRecipe { protected override void Run(ISessionFactory sessionFactory) { 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...