I have a very simple question but cannot find a simple answer.
I have NHibernate executing a raw SQL query, which unfortunately is loaded from the DB (yes, we store SQL query in the DB, not the best design but bear with me). This means that basically I have no idea how many columns the query will return.
What I know is that if the query is a single column then it is what I need and if it is more than one column then I need the first one, easy enough.
In my code I have basically 3 options:
session.CreateSQLQuery(SQLString).List();
session.CreateSQLQuery(SQLString).List<object>();
session.CreateSQLQuery(SQLString).List<object[]>();
Problem is that the List() will return either a List<int> (or the appropriate type, but int should be in my case) if the query returns a single column, or a List<object[]>() if I have multiple columns. Same goes for List<object> except that it will not return a List<int> in this case.
Of course trying to always cast to object[] (3rd option) and get the first element does not work, since nHibernate returns an int and that cannot be cast to object[].
Is there a way to force nHibernate to always return an object[] even in the case of a single column? If not, is there an easy way to check the number of columns in the result and act accordingly?
Thanks!
You should take a look at the differant result transformers NHibernate provides out of the box (you can write your own as well of course).
What might fit in your case would be the
NHibernate.Transform.ToListResultTransformer. AFAIK, it transforms your result to an IList, where each entry contains an IList again.So: