NHibernate SQL查询在单列结果上的映射 [英] NHibernate SQL Query mapping on Single Column Result
问题描述
我有一个非常简单的问题,但找不到简单的答案.
I have a very simple question but cannot find a simple answer.
我让NHibernate执行一个原始SQL查询,不幸的是,该查询是从DB加载的(是的,我们将SQL查询存储在DB中,不是最好的设计,但请耐心等待).这意味着基本上我不知道查询将返回多少列. 我知道的是,如果查询是单个列,那么它就是我所需要的;如果查询不止一个列,那么我需要第一列,这很容易.
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.
在我的代码中,我基本上有3个选择:
In my code I have basically 3 options:
session.CreateSQLQuery(SQLString).List();
session.CreateSQLQuery(SQLString).List<object>();
session.CreateSQLQuery(SQLString).List<object[]>();
问题在于,如果查询返回单列,则List()将返回List<int>
(或适当的类型,但对于我而言应为int);如果我返回多列,则将返回List<object[]>()
. List<object>
也一样,除了在这种情况下不会返回List<int>
.
当然,尝试始终强制转换为object [](第三个选项)并获取第一个元素是行不通的,因为nHibernate返回一个int且不能强制转换为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[].
是否有一种方法可以强制nHibernate即使在单列情况下也总是返回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?
谢谢!
推荐答案
您应该看看NHibernate提供的不同结果转换器(当然,您也可以编写自己的代码).
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).
NHibernate.Transform.ToListResultTransformer
可能适合您的情况. AFAIK,它将您的结果转换为一个IList,其中每个条目再次包含一个IList.
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.
所以:
IList items = session
.CreateSQLQuery(query)
.SetResultTransformer(new NHibernate.Transform.ToListResultTransformer())
.List()
if(((Ilist)items[0]).Count == 1)
// just one columns
else
// more columns or zero
这篇关于NHibernate SQL查询在单列结果上的映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!