Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nhibernate transform result in a dictionnary

Tags:

nhibernate

Hello I would like how to have a specific output in nhibernate

var hql = @"select t1.info1, t2.info2
                    from table1 t1
                    left outer join t1.table2 t2";
var variable = session.CreateQuery(hql).List();

That query return an object array which contains another array. ie : in the first line, info1 can be retrieved by variable[0][0] and in the same line, info2 can be retrieved by variable[0][1]

I know that I can create a new Class like

class SpecificQuery
{
  public int info1;
  public int? info2
}

and then call :

session.CreateQuery(hql)
.SetResultTransformer(new AliasToBeanResultTransformer(typeof(SpecificQuery))).List();

But I don't want to create a specific class each time I want to have a special return.

Does someone know a solution to that problem ? For example, a IList< Dictionnary< string, object>>[] In this case, the first line of info1 can be retrieve by variable0 (in case of variable[0][0]

Thanks

like image 807
P. Sohm Avatar asked Nov 30 '25 14:11

P. Sohm


2 Answers

You can use the AliasToEntityMapResultTranformer

session.CreateQuery(hql)
   .SetResultTransformer(Transformers.AliasToEntityMap).List();

This will return a list of IDictionary objects.

like image 173
Vadim Avatar answered Dec 03 '25 07:12

Vadim


NHibernate offers the Tuple class that could be used here:

var hql = @"select t1.info1 as First, t2.info2 as Second
                from table1 t1
                left outer join t1.table2 t2";

// instead of Tuple<String, decimal> you can use other types of course
var variable = session.CreateQuery(hql)
        .SetResultTransformer(new AliasToBeanResultTransformer(
             typeof(NHibernate.Linq.Tuple<String, decimal>)))
        .List<NHibernate.Linq.Tuple<String, decimal>>();

You would then access the items with

variable[0].First
variable[0].Second
like image 43
Florian Lim Avatar answered Dec 03 '25 08:12

Florian Lim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!