title: NHibernate/FluentNHibernate property bag
body: <p>Given a Vehicle class and a VehicleProperty class...</p>
  
  <pre><code>public class Vehicle
  {
      public virtual int Id { get; protected set; }
      public virtual string Registration { get; set; }
  
      private List&lt;VehicleProperty&gt; _properties = new List&lt;VehicleProperty&gt;();
      public virtual IEnumerable&lt;VehicleProperty&gt; Properties
      {
          get { return _properties; }
          protected set{ _properties = new List&lt;VehicleProperty&gt;(value);}
      }
  
      public virtual void AddProperty(string name, string value)
      {
          _properties.Add(new VehicleProperty {Name = name, Value = value});
      }
  }
  
  public class VehicleProperty
  {
      public virtual string Name { get; set; }
      public virtual string Value { get; set; }
  }
  </code></pre>
  
  <p>How can I map the two classes so that the VehicleProperty table has a composite key of [VehicleId] and [Name]. Vehicle would be an aggregate root (VehicleProperty is not accessed outside of a Vehicle class).</p>
  
  <p>I have tried everything that I can think of (I'm new to NHibernate so that's not much)</p>
  
  <pre><code>public class VehicleMap : ClassMap&lt;Vehicle&gt;
  {
      public VehicleMap()
      {
          Id(x =&gt; x.Id);
          Map(x =&gt; x.Registration);
          HasMany(x =&gt; x.Properties)
              .Inverse()
              .Cascade.All();
      }
  }
  
  public class VehiclePropertyMap : ClassMap&lt;VehicleProperty&gt;
  {
      public VehiclePropertyMap()
      {
          UseCompositeId()
              .WithKeyProperty(x =&gt; x.Name)
              .WithKeyReference(x =&gt; x.Vehicle, "Vehicle_Id");
          Map(x =&gt; x.Name);
          Map(x =&gt; x.Value);
      }
  }
  </code></pre>
  
  <p>This mapping results in the below sql and a StaleStateException "Unexpected row count: 0; expected: 1" (I also don't really want to have a Vehicle property on the VehicleProperty)...</p>
  
  <pre><code>INSERT INTO "Vehicle" (Registration) VALUES (@p0); select last_insert_rowid(); @p0 = 'AA09CDE'
  UPDATE "VehicleProperty" SET Name = @p0, Value = @p1 WHERE Name = @p2 AND Vehicle_Id = @p3; @p0 = 'Colour', @p1 = 'Black', @p2 = 'Colour', @p3 = ''
  </code></pre>