NHibernate hql元组结果
hql = "select f, b from Foo f, Bar b" var resultList = session.CreateQuery(hql).List();
result list item是一个数组,其中[0]的类型为Foo,[1] id为Type Bar
有没有办法使用Tuple (或其他generics类)作为object []的通用参数,以便可以跳过转换?
是的,你可以,像:
// The new Tuple(foo, bar) constructor Type constructor = typeof(Tuple).GetConstructors()[0];
然后
.SetResultTransformer(Transformers.AliasToBeanConstructor(constructor));
在.List()
之前
附录
我查看了我的代码(因为我已经在一两年前完成了这个:)),我注意到我更喜欢
Type constructor = typeof(Tuple).GetConstructor(new[] { typeof(Foo), typeof(Bar) });
有一个很好的理由:现在(从.NET 4.5.1开始), Tuple
有一个公共构造函数,它是new Tuple(T1 t1, T2 t2)
。 没有隐含或明确的保证,在未来的.NET版本中,将不会有一个Tuple
的无参数公共构造函数,它将返回一个“空”元组。 较长的GetConstructor
表单保证始终采用“正确”的构造函数。