title: (Fluent) NHibernate: HasMany/References (bidirectional) + Cascade Save
body: <p>How do I configure mappings for bidirectional mapping in the scenario of <em>X references Y, Y has many Xs</em>, so that when I add many Xs to the Y instance and save Y instance, it'll work properly?</p>
  
  <p>to make the problem clear, here's the code:</p>
  
  <p><strong>ClientCompany</strong> model has <code>HasMany</code> <strong>ContactPerson</strong> related models:</p>
  
  <pre><code>public class ClientCompany
  {
      // .... 
      public virtual ISet&lt;ContactPerson&gt; ContactPeople { get; set; }
  }
  
  // mapping:
  HasMany(x =&gt; x.ContactPeople)
              .AsSet()
              .Inverse()
              .Cascade.All();
  </code></pre>
  
  <p>the <strong>ContactPerson</strong> has not-nullable "ClientCompany" field referencing the parent company:</p>
  
  <pre><code>public class ContactPerson
  {
      // ....
      public virtual ClientCompany ClientCompany { get; set; }
  }
  
  References(x =&gt; x.ClientCompany).Not.Nullable();
  </code></pre>
  
  <p>calling this code:</p>
  
  <pre><code>sess.Save(new ClientCompany()
              {                    
                  ContactPeople = new HashSet&lt;ContactPerson&gt;()
                  {
                      new ContactPerson()
                  }
              });
  </code></pre>
  
  <p>causes this exception:</p>
  
  <blockquote>
    <p>not-null property references a null or transient value
    xxxx.ContactPerson.ClientCompany</p>
  </blockquote>
  
  <p>this is just simplified case, I'm using AutoMapper in my real-world project so <strong>setting the reference manually</strong> is <strong>not the solution</strong></p>