NHibernate HQL元组结果 [英] NHibernate hql tuple result
问题描述
hql = "select f, b from Foo f, Bar b"
var resultList = session.CreateQuery(hql).List<object[]>();
结果列表项是一个数组,其中[0]是Foo类型,[1] id是类型栏
result list item is an array where [0] is of type Foo and [1] id of Type Bar
有没有一种方法可以使用Tuple< Foo,Bar> (或其他通用类)作为由object []插入的通用参数,因此可以跳过强制转换吗?
Is there a way to use Tuple<Foo,Bar> (or other generic class ) as generic parameter insted of object[] so one can skip casting?
推荐答案
可以,例如:
// The new Tuple<Foo, Bar>(foo, bar) constructor
Type constructor = typeof(Tuple<Foo, Bar>).GetConstructors()[0];
然后
.SetResultTransformer(Transformers.AliasToBeanConstructor(constructor));
在.List()
附录
我查看了我的代码(因为一两年前已经完成了:)),我注意到我更喜欢
I've looked at my code (because I've already done this one or two years ago :) ), and I noticed that I preferred
Type constructor = typeof(Tuple<Foo, Bar>).GetConstructor(new[] { typeof(Foo), typeof(Bar) });
对此有一个很好的理由:现在(从.NET 4.5.1开始),有一个Tuple<T1, T2>
的公共构造函数,即new Tuple(T1 t1, T2 t2)
. 没有隐式或显式保证,在.NET的将来版本中,不会有Tuple<T1, T2>
的无参数公共构造函数来返回空"元组.较长的GetConstructor
格式可确保始终采用正确的"构造函数.
There is a perfectly good reasoning for this: now (as of .NET 4.5.1) there is a single public constructor for Tuple<T1, T2>
, that is new Tuple(T1 t1, T2 t2)
. There is no implicit or explicit guarantee that in a future version of .NET there won't be a parameterless public constructor of Tuple<T1, T2>
that will return an "empty" tuple. The longer GetConstructor
form guarantees that the "right" constructor will always be taken.
这篇关于NHibernate HQL元组结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!