title: How do I use Fluent NHibernate to map a self-referencing folder hierarchy?
body: <p>I have a folder hierarchy represented by the following class:</p>
  
  <pre><code>public class Folder
  {
      public virtual int Id { get; set; }
      public virtual string Name { get; set; }
      public virtual Folder ParentFolder { get; set; }
      public virtual ICollection&lt;Folder&gt; SubFolders { get; set; }
  }
  </code></pre>
  
  <p>In other words, each <code>Folder</code> can belong to a <code>ParentFolder</code>, as well as have <code>SubFolders</code> under it. I'm using Fluent NHibernate's <code>Automapper</code> and automatically generating the database schema using <code>SchemaExport</code>. I get the following table when I try to save some test folders:</p>
  
  <pre><code>Id | Name                        | ParentFolder_id | Folder_id
  ----------------------------------------------------------------
  1  | Root Folder (has children)  | NULL            | NULL
  2  | Root Folder (no children)   | NULL            | NULL
  3  | Sub Folder                  | 1               | NULL
  4  | Sub Sub Folder              | 2               | NULL
  </code></pre>
  
  <p>So far so good, the <code>ParentFolder_id</code> column is being set correctly, although I don't know why it created another <code>Folder_id</code> column. Now, when I try to run the following code:</p>
  
  <pre><code>using (var session = SessionFactory.OpenSession())
  {
      // I'm using NHibernate 3
      var rootFolder = session.Query&lt;Folder&gt;()
                              .Where(x =&gt; x.Name.StartsWith("root").First();
  
      Console.WriteLine(rootFolder.SubFolders.Count());
  }
  </code></pre>
  
  <p>The count returned is 0, and the following SQL is executed:</p>
  
  <pre><code>SELECT count(Id) FROM [Folder] WHERE Folder_id = 1
  </code></pre>
  
  <p>This SQL statement is wrong. It should be doing:</p>
  
  <pre><code>SELECT count(Id) FROM [Folder] WHERE ParentFolder_id = 1
  </code></pre>
  
  <p>Can anyone tell me why Fluent NHibernate is creating the extra <code>Folder_id</code> column and querying on it, and how I can fix it so that it properly queries the <code>ParentFolder_id</code> column instead? I've tried the following override with no luck:</p>
  
  <pre><code>public class FolderOverride : IAutoMappingOverride&lt;Folder&gt;
  {
      public void Override(AutoMapping&lt;Folder&gt; mapping)
      {
          mapping.HasMany(x =&gt; x.SubFolders).Inverse(); // I thought inverse might fix it, but no dice
          mapping.References(x =&gt; x.ParentFolder);
      }
  }
  </code></pre>