我有一个包含所有不同帐户名称前缀 (a-z) 的列表,我使用这些前缀获取的
var accounts = this.SessionManager.GetActiveSession().QueryOver<Account>();
var q = accounts.Select(Projections.Distinct(
Projections.SqlFunction("substring",
NHibernateUtil.String,
Projections.Property("Name"),
Projections.Constant(1),
Projections.Constant(1))));
但是,我想要做的不是返回不同的列表,而是对前缀进行分组并返回以该前缀开头的帐户数量,但我不确定如何通过使用查询来执行分组,因为它不像标准那么简单林克。
我使用 QueryOver 而不是 Query 的原因是因为出于某种原因,子字符串函数是在内存中而不是在数据库服务器上执行的。
这就是我通常会做的
var prefixes = (from acc in this.SessionManager.GetActiveSession().Query<Account>()
group acc by acc.Name.Substring(0, 1)
into grp
select new
{
Prefix = grp.Key,
Count = grp.Count()
});
Edit这是我尝试过的,但收到以下错误
表达式中无法识别的方法调用 SqlFunction("substring", NHibernateUtil.String, new [] {Property("Name"), Constant(Convert(1)), Constant(Convert(1))})
var accounts = this.SessionManager.GetActiveSession().QueryOver<Account>().Select(
Projections.Group<string>(x => Projections.SqlFunction("substring", NHibernateUtil.String,
Projections.Property("Name"), Projections.Constant(1),
Projections.Constant(1))),
Projections.Count<string>(x => Projections.SqlFunction("substring", NHibernateUtil.String,
Projections.Property("Name"), Projections.Constant(1),
Projections.Constant(1)))
);