Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate hql tuple result

Tags:

c#

nhibernate

hql = "select f, b from Foo f, Bar b"

var resultList = session.CreateQuery(hql).List<object[]>();

result list item is an array where [0] is of type Foo and [1] id of Type Bar

Is there a way to use Tuple<Foo,Bar> (or other generic class ) as generic parameter insted of object[] so one can skip casting?

like image 536
wiero Avatar asked Oct 16 '25 15:10

wiero


1 Answers

Yes you can, something like:

// The new Tuple<Foo, Bar>(foo, bar) constructor
Type constructor = typeof(Tuple<Foo, Bar>).GetConstructors()[0];

and then

.SetResultTransformer(Transformers.AliasToBeanConstructor(constructor));

before the .List()

addendum

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) });

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.

like image 84
xanatos Avatar answered Oct 19 '25 06:10

xanatos