title: Dynamic HasMany mapping using reflection in Fluent NHibernate
body: <p>I am using NHibernate 3.3 and trying to map my class hierarchy to DB via reflection as follows:</p>
  
  <pre><code>class Parent
  {
      public virtual IList&lt;Child&gt; Children { get; set; }
  }
  
  class Child
  {
      public virtual Parent MyParent { get; set; }
  }
  
  public class ParentMap : ClassMap&lt;Parent&gt;
  {
      public ParentMap()
      {
          Helper.Map(this);
      }
  }
  
  public class Helper
  {
      public static void Map&lt;T&gt;(ClassMap&lt;T&gt; map)
      {
          foreach (var property in typeof(T).GetProperties())
          {
              // creating lambda x =&gt; x.Children
  
              var arg = Expression.Parameter(typeof(T), "x");
              Expression expr = Expression.Property(arg, property);
  
              // Func&lt;Parent, IList&lt;Child&gt;&gt; does not work in HasMany()
              // var type = typeof(Func&lt;,&gt;).MakeGenericType(typeof(T), property.PropertyType);
  
              // but IEnumerable works
              var type = property.PropertyType.GetGenericArguments()[0];  // Child
              type = typeof(IEnumerable&lt;&gt;).MakeGenericType(type);         // IEnumerable&lt;Child&gt;
              type = typeof(Func&lt;,&gt;).MakeGenericType(typeof(T), type);    // Func&lt;Parent, IEnumerable&lt;Child&gt;&gt;
  
              dynamic lambda = Expression.Lambda(type, expr, arg);
              map.HasMany(lambda);
          }
      }
  }
  </code></pre>
  
  <p>The above is just a simplified example, the main idea is to call HasMany() dynamically for every collection property. I can't seem to find a more direct way of doing that but it works.</p>
  
  <p>The problem is that when I apply Cascade.All() to the map, it results in a StackOverflow exception. When mapping is done manually, this works just fine, so it is not likely to be a mismapping problem.</p>