title: Object lifecycle in NHibernate
body: <p>I think I'm missing something conceptually regarding NHibernate. I have an <code>Instrument</code> object which maps to an <code>instruments</code> table in my database. I also have a <code>BrokerInstrument</code> object which maps to my <code>brokerInstruments</code> table in my database. <code>brokerInstrumnets</code> is a child table of <code>instruments</code>. My classes look like:</p>
  
  <pre><code>public class Instrument : Entity
  {
      public virtual string Name { get;  set; }
      public virtual string Symbol {get;  set;}
      public virtual ISet&lt;BrokerInstrument&gt; BrokerInstruments { get; set; }
      public virtual bool IsActive { get; set; }        
  }
  
  public class BrokerInstrument : Entity
  {
      public virtual Broker Broker { get; set; }
      public virtual Instrument Instrument { get; set; }
      public virtual decimal MinIncrement { get; set; }
  }
  </code></pre>
  
  <p>In my unit test, if I retrieve an <code>Instrument</code> from the database and then delete it with <code>ISession.Delete</code>, it is removed from the database along with the children (I have cascade-all switched on in my mapping file). The <code>Instrument</code> however still exists in memory. For example:</p>
  
  <pre><code>    [Test]
      public void CascadeTest()
      {
          int instrumentId = 1;
          IInstrumentRepo instruments = DAL.RepoFactory.CreateInstrumentRepo(_session);
          Instrument i = instruments.GetById&lt;Instrument&gt;(instrumentId); // retrieve an instrument from the db
          foreach (BrokerInstrument bi in i.BrokerInstruments)
          {
              Debug.Print(bi.MinIncrement.ToString()); // make sure we can see the children
          }
  
          instruments.Delete&lt;Instrument&gt;(i); // physically delete the instrument row, and children from the db
  
          IBrokerInstrumentRepo brokerInstruments = DAL.RepoFactory.CreateBrokerInstrumentRepo(_session);
          BrokerInstrument deletedBrokerInstrument = brokerInstruments.GetById&lt;BrokerInstrument&gt;(1); // try and retrieve a deleted child
          Assert.That(instruments.Count&lt;Instrument&gt;(), Is.EqualTo(0)); // pass (a count in the db = 0)
          Assert.That(brokerInstruments.Count&lt;BrokerInstrument&gt;(), Is.EqualTo(0)); // pass (a count of children in the db = 0)
          Assert.That(i.BrokerInstruments.Count, Is.EqualTo(0)); // fail because we still have the i object in memory, although it is gone from the db
  
      }
  </code></pre>
  
  <p>What is best practise regarding the object in memory? I am now in an inconsistent state because I have an <code>Instrument</code> object in memory which does not exist in the database. I'm a novice programmer so verbose answers with links are much appreciated.</p>