title: fluent nhibernate many-to-many with a following many-to-many mapping
body: <p>I have a many-to-many hierarchical situation I just can't figure out how to solve mapping wise.</p>
  
  <p>I have an entity Incident. This Incident can have many Events. An event is nothing but a value object so i created a many-to-many mapping which works perfectly fine. </p>
  
  <p>Now comes the bit i cant figure out... Every Event selected for an Incident can have multiple Causes (which is a value object as well)</p>
  
  <p>Below is the simplified datamodel (events and causes are both stored in SystemValues and have Type as their discriminatorvalue):
  <img src="https://i.stack.imgur.com/pGgOW.jpg" alt="enter image description here"></p>
  
  <p>(ID in table IncidentEvent is a surrogate primary key to avoid hassle with a composite key)</p>
  
  <p>My mapping is as follows (simplified):
  Incident:</p>
  
  <pre><code>public class IncidentMap : ClassMap&lt;Incident&gt; {
  
      public IncidentMap() {
      Table("Incident");
      Id(x =&gt; x.ID).GeneratedBy.Identity();
  
          HasManyToMany(x =&gt; x.Event)
          .Table("IncidentEvent")
          .ParentKeyColumn("IncidentID")
          .ChildKeyColumn("EventID");
      }
  }
  </code></pre>
  
  <p>Event (subclassmapped from a general 'SystemValueMap'):</p>
  
  <pre><code>public class EventMap : SubclassMap&lt;StoryWhere&gt; {
      public EventMap() {
          DiscriminatorValue((int)SystemValue.Type.Event);
          HasManyToMany(x =&gt; x.Incident)
          .Table("IncidentEvent")
          .ParentKeyColumn("IncidentID")
          .ChildKeyColumn("EventID");
  
          HasManyToMany(x =&gt; x.Cause)
              .Table("IncidentEventCause")
              .ParentKeyColumn("IncidentEventID")
              .ChildKeyColumn("CauseID");
      }
  }
  </code></pre>
  
  <p>Cause:</p>
  
  <pre><code>public class CauseMap : SubclassMap&lt;Cause&gt; { 
      public CauseMap() { DiscriminatorValue((int)SystemValue.Type.Cause); }
  }
  </code></pre>
  
  <p>As you can see the mapping for 'Event' is a mess and of course it doesnt work. When an insert is done, I get foreignkey contraints as NHibernate tries to insert EventID into columns IncidentEventID of table IncidentEventCause. I probably need to tell Nhibernate how to use IncidentEventID instead. 
  I need to make the Event be aware of it's many-to-many relation with incident and of it's following relation with Cause, but I'm afraid I don't know how.</p>
  
  <p>Hoping someone can point me in the right direction.</p>