[英]How to write the following SQL query in NHibernate
Hey - I'm battling to figure out how to write the following using NHibernate ICriteria (Multi criteria?) for the following: 嘿-我正在努力找出如何使用NHibernate ICriteria(多条件?)编写以下内容的方法:
(It's a query to get a list of first names ordered by popularity in the table in the last day) (这是一个查询,以获取在过去一天的表中按受欢迎程度排序的名字的列表)
select firstname,count(firstname) as occurances from registrants
where timestamp between DateAdd(day,-1, GetDate()) and getdate()
group by firstname
order by count(firstname) desc
Also, given this is just a couple of columns from a table, excluding the ID, and NHibernate needs ID's for it's objects, what's the easiest way to "fake" an ID so I can just get the results? 另外,鉴于这只是表中的几列,不包括ID,并且NHibernate需要ID作为对象,因此“伪造” ID以便获得结果的最简单方法是什么?
You need to use projections and a transformer to do this. 您需要使用投影和变压器来执行此操作。 Here's some background info http://nhibernate.info/doc/nh/en/index.html#querycriteria-projection 这是一些背景信息http://nhibernate.info/doc/nh/en/index.html#querycriteria-projection
var criteria = Session.CreateCriteria<Registrant>()
.Add(Restrictions.Between("Timestamp", DateTime.Now.AddDays(-1), DateTime.Now)
.AddOrder(Order.Desc(Projections.Count("FirstName")))
.SetProjection(Projections.ProjectionList()
.Add(Projections.GroupProperty("FirstName"), "FirstName")
.Add(Projections.Count("FirstName"), "Occurances")
.SetResultTransformer(Transformers.AliasToBean<FirstNameOccurance>());
criteria.List<FirstNameOccurance>();
You'll need to create a class called FirstNameOccurance that has 2 properties called FirstName and Occurances. 您需要创建一个名为FirstNameOccurance的类,该类具有2个名为FirstName和Occurances的属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.