title: Fluent NHibernate One-To-Many Mapping
body: <p>I have the following 2 classes:</p>
  
  <p><strong>Advert</strong>  </p>
  
  <pre><code>public virtual int Id { get; set;
  public virtual IList&lt;AdvertImage&gt; AdvertImages { get; set; }
  </code></pre>
  
  <p><strong>AdvertImage</strong>  </p>
  
  <pre><code>public virtual int Id { get; set; }
  public virtual string Filename { get; set;
  public virtual Advert Advert { get; set; }
  </code></pre>
  
  <p>In the DB, my AdvertImages table has the FK 'AdvertId' which relates to the Adverts table which has the PK of 'Id'.</p>
  
  <p>This is a One-To-Many mapping, in that one advert can have many images.</p>
  
  <p>My Fluent NHibernate mappings (edited for brevity) are:</p>
  
  <p><strong>AdvertMap</strong>  </p>
  
  <pre><code>Id(x =&gt; x.Id)
    .GeneratedBy.Identity();
  ...
  HasMany(x =&gt; x.AdvertImages)
    .KeyColumn("AdvertId")
    .Inverse();
  ...
  Table("Adverts");
  </code></pre>
  
  <p><strong>AdvertImageMap</strong>  </p>
  
  <pre><code>Id(x =&gt; x.Id)
    .GeneratedBy.Identity();
  ...
  References(x =&gt; x.Advert)
    .Column("AdvertId");
  ...
  Table("AdvertImages");
  </code></pre>
  
  <p>I am creating a new instance of <code>Advert</code> in code, then populating the <code>AdvertImages</code> property (of Advert) with a <code>List&lt;AdvertImage&gt;</code>.</p>
  
  <p>When I go to persist my <code>Advert</code> object to the DB, I would like the AdvertImages to be inserted into their AdvertImages table, but due to the relationship between the 2 tables, I need the Advert insertion to happen first, so as the PK Id is generated, which can then be inserted in the AdvertImages table. (When I create my list of AdvertImage, I am populating the Filename property, but obviously don't have the new AdvertId at that stage, so want that to be populated when the advert is persisted to the DB).</p>
  
  <p>I have tried experimenting with different Inverse() and Cascade settings but haven't succeeded yet. Can anyone help please?</p>