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 StaleObjectStateExceptions.

Getting ready

Follow the Getting ready step in the Save entities to the database recipe in this chapter.

How to do it…

  1. Add a new folder named MergingEntities to the SessionRecipes project.
  2. 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) ...

Get NHibernate 4.x Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.