C# Fluent NHibernate中使用反射的动态HasMany映射
我正在使用NHibernate 3.3,并试图通过反射将我的类层次结构映射到DB,如下所示:C# Fluent NHibernate中使用反射的动态HasMany映射,c#,nhibernate,reflection,fluent,C#,Nhibernate,Reflection,Fluent,我正在使用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> { publ
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);
}
}
}
类父类
{
公共虚拟IList子项{get;set;}
}
班童
{
公共虚拟父级MyParent{get;set;}
}
公共类ParentMap:ClassMap
{
公共ParentMap()
{
Helper.Map(this);
}
}
公营助理员
{
公共静态无效映射(类映射映射)
{
foreach(typeof(T).GetProperties()中的var属性)
{
//创建lambda x=>x.子对象
var arg=表达式参数(typeof(T),“x”);
Expression expr=Expression.Property(arg,Property);
//Func在HasMany()中不起作用
//var type=typeof(Func).MakeGenericType(typeof(T),property.PropertyType);
//但我有无数的作品
var type=property.PropertyType.GetGenericArguments()[0];//子对象
type=typeof(IEnumerable)。MakeGenericType(type);//IEnumerable
type=typeof(Func).MakeGenericType(typeof(T),type);//Func
动态lambda=Expression.lambda(type,expr,arg);
HasMany地图(lambda);
}
}
}
以上只是一个简化的示例,其主要思想是为每个集合属性动态调用HasMany()。我似乎找不到一个更直接的方法,但它是有效的
问题是,当我对映射应用Cascade.All()时,它会导致StackOverflow异常。当手动完成映射时,这很好,因此不太可能是映射不匹配的问题。实际上它与NHibernate无关,因为它在流畅地调用.Configure().Mappings().BuildConfiguration()时失败。我使用的是最新版本的Fluent(1.3.0.733)。