title: Attaching a disconnected object to an NHibernate session; best practice?
body: <p>My repository works in a <code>UnitOfWork</code> model; all operations, whether retrieval or persistence, must be performed within the scope of an <code>IDisposable</code> <code>UnitOfWork</code> token object, which behind the scenes is associated with a <code>Session</code> that performs the work requested. So, the basic pattern is:</p>
  
  <pre><code>using (var uow = repo.BeginUnitOfWork())
  {
     try
     {
        //DB operations here; all repo methods require passing in uow.
        ...
        repo.CommitUnitOfWork(uow);
     }
     catch(Exception)
     {
        repo.RollbackUnitOfWork(uow);
        throw;
     }
  }
  </code></pre>
  
  <p>I've also implemented some wrapper methods that allow you to specify a lambda or delegate that will be executed in this framework, relieving the need to implement all this scaffolding every time.</p>
  
  <p>The problem I'm having is that using this model, code must "know" what the user needs, and eager-load it using <code>NHUtil.Initialize()</code> within the <code>UnitOfWork</code>. Once the UOW is disposed at the end of the using block, the Session associated with any <code>PersistentBags</code> is closed, and so they cannot be evaluated. As eager-loading everything up front is not always feasible and kind of defeats the purpose of a lazy-loading ORM, I am implementing an <code>Attach()</code> method.</p>
  
  <p>Here's the question; In the absence of a built-in <code>ISession.Attach()</code> method, there are three methods I've seen recommended to associate an object with a new Session. Which of them is the best practice to get the job done?</p>
  
  <p>A:</p>
  
  <pre><code>if(!Session.Contains(domainObject))
      Session.Update(domainObject);
  </code></pre>
  
  <p>B:</p>
  
  <pre><code>Session.Merge(domainObject);
  </code></pre>
  
  <p>C:</p>
  
  <pre><code>Session.Lock(domainObject, LockMode.None);
  </code></pre>