title: Mapping a single field to multiple tables with Fluent NHibernate
body: <p><strong>Question:</strong> is there a way to map a single foreign key to a number of mutually exclusive tables, based on a context?</p>
  
  <p><strong>Background...</strong></p>
  
  <p>In my specific example, I have the following domain graph, representing an insurance claim which can be against a vehicle <strong><em>or</em></strong> property:</p>
  
  <pre><code>public enum InvolvedPartyContext
  {
      Vehicle = 1,
      Property = 2
  }
  
  public class Claim
  {
      public virtual Guid Id { get; set; }
      public virtual InvolvedPartyContext InvolvedPartyContext { get; set; }
      public virtual Vehicle Vehicle { get; set; }    // set if Context = Vehicle
      public virtual Property Property { get; set; }  // set if Context = Property
  }
  
  public class Vehicle {  //... }
  
  public class Property {  //... }
  </code></pre>
  
  <p>The SQL looks like this (notice the single foreign key <em>InvolvedPartyId</em>):</p>
  
  <pre><code>CREATE TABLE Claims ( 
   Id uniqueidentifier NOT NULL,
   InvolvedPartyContext int NOT NULL,
   InvolvedPartyId uniqueidentifier NOT NULL
  )
  
  CREATE TABLE Vehicles (
      Id uniqueidentifier NOT NULL,
      Registration varchar(20) NOT NULL
  )
  
  CREATE TABLE Properties (
      Id uniqueidentifier NOT NULL,
      PostCode varchar(20) NOT NULL
  )
  </code></pre>
  
  <p>The Fluent NHibernate mapping file for Claim:</p>
  
  <pre><code>    public ClaimMap()
      {
          Id(x =&gt; x.Id);
          Map(x =&gt; x.InvolvedPartyContext).CustomTypeIs(typeof(InvolvedPartyContext));
          References(x =&gt; x.Vehicle, "InvolvedPartyId");
          References(x =&gt; x.Property, "InvolvedPartyId");
      }
  </code></pre>
  
  <p>This throws an "Invalid index {n} for this SqlParameterCollection with Count {m}" exception, since the same field (<em>InvolvedPartyId</em>) is mapped twice.  A simple fix would be to create VehicleId and PropertyId fields, but in the real world there are many more contexts, so this isn't very flexible.</p>