tags:

views:

39

answers:

2

Hi, I have simple HQL query:

var list = OpenSession()
              .CreateQuery("SELECT MAX(p.price) as max_price, 
                                   COUNT(p.id) as count_all 
                            FROM Order o left join o.Products p")
              .List();

I would like to output "max_price" and "count_all" columns/projections as easy as possible.

Something like:

Console.WriteLine(list[0]["max_price"]);
Console.WriteLine(list[0]["count_all]);

Any idea?

+1  A: 

Not sure about this but I think that you will need to create a class and project into that. This is how I would start by approaching it

class UserStatistics{
 MaxPrice {get; set;}
 CountAll {get; set;}
}

var list = OpenSession()
              .CreateQuery("SELECT MAX(p.price) as max_price, 
                                   COUNT(p.id) as count_all 
                            FROM Order o left join o.Products p")
              .SetResultTransformer(NHibernate.Transform.Transformers.AliasToBean(typeof(UserStatistics)))
              .List<UserStatistics>();

then it should be a matter of

Console.WriteLine(list[0].MaxPrice);
Console.WriteLine(list[0].CountAll);

Great Post explaining better.

Nathan Fisher
Also I needed to add:.SetResultTransformer(NHibernate.Transform.Transformers.AliasToBean(typeof(UserStatistics)));
knagode
added SetResultTransformer to answer. also included link to a post explaining it better.
Nathan Fisher
+2  A: 

You can transform it to Hashtable

.SetResultTransformer(AliasToEntityMap).List<HashTable>()[0]["max_price"];
Wayne
So I need to create a special class with projections first?(AliasToEntityMap??)
knagode
@knagode: No, AliasToEntityMap is a built in transformer; no need to do anything special.
DanP
Great! Before I had an error:The name 'AliasToEntityMap' does not exist in the current context. I had to change it to:.SetResultTransformer(NHibernate.Transform.Transformers.AliasToEntityMap)
knagode
+1 for being much simpler than mine for a simple result.
Nathan Fisher