title: Nhibernate mapping List<Class> where Class has its own table
body: <p>I'm trying to create mapping for classes:</p>
  
  <pre><code>public class Employer
      {
          public virtual int Id { get; protected set; }
          public virtual string Name { get; set; }
          public virtual IList&lt;Field&gt; Fields { get; set; }
          public virtual string Location { get; set; }
          public virtual string Phone { get; set; }
      }
  
  public class Field
      {
          public virtual int Id { get; protected set; }
          public virtual string Description { get; set; } 
      }
  </code></pre>
  
  <p>My mappings look like:</p>
  
  <pre><code>&lt;hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="lab" assembly="lab"&gt;
  
    &lt;class name="Employer" table="Employer"&gt;
      &lt;id name="Id"&gt;
        &lt;generator class="native"/&gt;
      &lt;/id&gt;
      &lt;property name="Name" /&gt;
  
      &lt;list name="Fields" cascade="all-delete-orphan"&gt;
        &lt;key column="EmployerId" /&gt;
        &lt;index column="FieldIndex" /&gt;
        &lt;one-to-many class="Field"/&gt;
      &lt;/list&gt;
  
      &lt;property name="Location" /&gt;
      &lt;property name="Phone" /&gt;
    &lt;/class&gt;
  
  &lt;/hibernate-mapping&gt;
  
  &lt;hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" namespace="lab" assembly="lab"&gt;
  
    &lt;class name="Field" table="Field"&gt;
      &lt;id name="Id"&gt;
        &lt;generator class="native"/&gt;
      &lt;/id&gt;
      &lt;property name="Description" /&gt;
    &lt;/class&gt;
  
  &lt;/hibernate-mapping&gt;
  </code></pre>
  
  <p>And code looks like:        </p>
  
  <pre><code>var session = configuration.BuildSessionFactory().OpenSession();
  var transaction = session.BeginTransaction();
  var emp = new Employer();
  emp.Name = "Mera";
  emp.Fields = new List&lt;Field&gt; ();
  emp.Fields.Add(new Field() { Description = "C#" });
  emp.Fields.Add(new Field() { Description = "C++" });
  emp.Location = "Street";
  emp.Phone = "02";
  session.Save(emp);
  transaction.Commit();
  
  var transaction2 = session.BeginTransaction();
  var emp2 = new Employer();
  emp2.Name = "Mera2";
  emp2.Fields = session.CreateQuery("from Field").List&lt;Field&gt;();
  emp2.Location = "Street";
  emp2.Phone = "02";
  session.Save(emp2);
  transaction2.Commit();
  </code></pre>
  
  <p>This code just substitutes old entries in Field table for new one for the second employer. So Field table still has 2 records and Employer table has 2 records.</p>
  
  <p>As you could understand I need that if 2 fields are equal (the same Description) both of 2 employers should have the same object references on it. </p>