title: Nhibernate - Saving object with dependant tables
body: <p>I have a User object that as one of the properties contains a Photos property, which is am IList type. </p>
  
  <p>The tables in the SQL database are joined by a foreign key. ie</p>
  
  <p>Table User { userid long NOT NULL....... } 
  Table UserPhoto { photoid long NOT NULL, userid long not null references [User].UserId........ }</p>
  
  <p>So you cannot insert a row in userphoto without the corresponding User row.</p>
  
  <p>What I want to be able to do is build up a User Object in code, add an Ilist of UserPhoto objects (which must neccesarily contain a blank user id, as does the User object as it hasn't been saved and created by identity insert yet)</p>
  
  <p>My mappings are as follows</p>
  
  <pre><code> &lt;class name="User" table="[User]"&gt;
      &lt;id name="UserId" column="Id"&gt;
        &lt;generator class="identity" /&gt;
      &lt;/id&gt;
      &lt;bag name="Photos" order-by="DisplayOrder asc" cascade="all"&gt;      
        &lt;key column="UserId" /&gt;
        &lt;one-to-many class="UserPhoto" /&gt;
      &lt;/bag&gt;
   &lt;/class&gt;
  &lt;class name="UserPhoto" table="UserPhoto"&gt;
      &lt;id name="PhotoId" column="Id"&gt;
        &lt;generator class="identity" /&gt;
      &lt;/id&gt;
      &lt;property name="UserId" /&gt;
  &lt;/class&gt;
  </code></pre>
  
  <p>But when I try and save the User object with Nhibernate Session.Save(user), it throws an error saying Foreign key constraint failed. So im guessing its trying to insert either the user photos in the list before the user table, OR its not setting the newly generated user id property in the photos and trying to save them with a null user id. </p>
  
  <p>Do you have to have something extra in the mapping to show that this is a foreign key column and what it applies to, so nhibernate knows how to insert the dependant rows in the right order so I can accomplish this in one insert?</p>