我正在使用NHibernate 3.3并尝试通过反射将我的类层次结构映射到DB:
class Parent
{
public virtual IList<Child> Children { get; set; }
}
class Child
{
public virtual Parent MyParent { get; set; }
}
public class ParentMap : ClassMap<Parent>
{
public ParentMap()
{
Helper.Map(this);
}
}
public class Helper
{
public static void Map<T>(ClassMap<T> map)
{
foreach (var property in typeof(T).GetProperties())
{
// creating lambda x => x.Children
var arg = Expression.Parameter(typeof(T), "x");
Expression expr = Expression.Property(arg, property);
// Func<Parent, IList<Child>> does not work in HasMany()
// var type = typeof(Func<,>).MakeGenericType(typeof(T), property.PropertyType);
// but IEnumerable works
var type = property.PropertyType.GetGenericArguments()[0]; // Child
type = typeof(IEnumerable<>).MakeGenericType(type); // IEnumerable<Child>
type = typeof(Func<,>).MakeGenericType(typeof(T), type); // Func<Parent, IEnumerable<Child>>
dynamic lambda = Expression.Lambda(type, expr, arg);
map.HasMany(lambda);
}
}
}
以上只是一个简化示例,主要思想是为每个集合属性动态调用HasMany()。我似乎无法找到更直接的方法,但它有效。
问题在于,当我将Cascade.All()应用于地图时,会导致StackOverflow异常。当手动完成映射时,这很好用,因此不太可能是错误映射问题。