NHibernate:返回已应用聚合函数的强类型列表 [英] NHibernate: returning a strongly typed list having applied an aggregate function
问题描述
我想让nHibernate从使用HQL的CreateQuery调用返回一个强类型列表.
I'd like to have nHibernate return a strongly typed list from a CreateQuery invocation using HQL.
我们希望返回一个强类型的"MyType"列表,但我们希望在返回结果集之前将聚合函数应用于结果集.不幸的是,据我了解,添加聚合字段意味着nHibernate无法将结果与我们的"MyType"类型的签名匹配.
We'd like a strongly typed list of "MyType" returned, but we'd like to apply an aggregate function to the resultset before it's returned. Unfortunately, as I understand it, adding the aggregate field means nHibernate is unable to match the results to the signature of our "MyType" type.
我们如何解决这个问题?以下查询描述了我们希望从数据库返回的内容-但是"feedcount"字段会影响nHibernate确定要返回的类型列表的能力.
How do we get around this? The following query describes what we'd like to return from the database - but the "feedcount" field affects nHibernate's ability to determine the typed list to return.
select feedname, count(feedurl) as feedcount from rsssubscriptions group by feedurl, feedname order by feedcount desc
大概必须在事件序列中更早地生成结果集,以确保nHibenate可以推断出正确的类型以为每个记录实例化.
Presumably the resultset has to be generated earlier in the sequence of events, to ensure nHibenate can infer the correct type to instantiate for each record.
谢谢
推荐答案
这是您需要做的:
IList<MyObj> reults = Session.CreateQuery("select r.feedname as feedname, count(r.feedurl) as feedcount from rsssubscriptions r group by r.feedname")
.SetResultTransformer(NHibernate.Transform.Transformers.AliasToBean(typeof(myobj)))
.List<MyObj>();
然后像这样定义MyObj类型:
And then define the MyObj type like this:
public class MyObj
{
public virtual long feedcount { get; set; }
public virtual string feedname { get; set; }
}
上述类型的属性名称必须与返回的属性的别名相同,并且所有属性都必须是虚拟的.
The property names of the above type must be the same as the aliases of your returned properties and all properties must be virtual.
阅读以下文章,详细了解您可以使用SetResultTransformer()方法执行的操作: http://www.junasoftware.com/blog/nhibernate-setresulttransformer-和-dto.aspx
Read the following post on more info on what you can do with the SetResultTransformer() method: http://www.junasoftware.com/blog/nhibernate-setresulttransformer-and-dto.aspx
这篇关于NHibernate:返回已应用聚合函数的强类型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!