NHibernate LINQ 计算查询中的组数
NHibernate LINQ count number of groups in query
我是 运行 关于 table 的报告,并按两列分组。我想获得结果中的组总数,以便我可以对报告进行分页。但是 .Count() 方法返回第一组中的行数。查询是
return data.GroupBy(x => new { x.Item.Parent.Name, x.Date })
.Select(x => new Item
{
Parent = x.Key.Name,
Date = x.Key.Date,
PredictedSales = x.Sum(y => y.PredictedSales),
RealSales = x.Sum(y => y.ActualSales),
});
.Count() 正在执行以下查询
select cast(count(*) as INT) as col_0_0_
from dbo.[table1] table1
left outer join dbo.[Table2] table2
on table1.Table2Id = table2.Id
and 0 /* @p0 */ = table2.Deleted
left outer join dbo.[Table3] table3
on table2.Table3Id = table3.Id
where table1.Date >= '2017-03-01T00:00:00' /* @p2 */
and table1.Date <= '2017-03-15T00:00:00' /* @p3 */
and (table1.VariancePercentage is not null)
and abs(table1.VariancePercentage * 100 /* @p4 */) <= 5 /* @p5 */
group by table3.Name,
table1.Date
而我想要的是 select TOP(1) COUNT(*) OVER () FROM.
有什么方法可以使用 linq 查询来实现吗?
这是一个已知问题,NH-3154。
您的案例需要从子查询中计数。据我所知,hql does not support it (subqueries are supported only in select
expression or where
conditions), so it will likely not be supported soon. (linq-to-nhibernate translates to hql.)
因此您必须使用 sql 本机查询进行计数 (session.CreateSQLQuery("...")
),或者在功能和性能上做出一些妥协:
- 选择可供浏览的最大页数。
- 发出以下查询:
var maxResults = maxPageCount * pageSize + 1;
var count = data.GroupBy(x => new { x.Item.Parent.Name, x.Date })
.Select(x => x.Key)
.Take(maxResults)
.ToList()
.Count();
- 如果
count == maxResults
,您可以告诉您的用户还有更多页面。
当然,这将发出一个查询,加载所有分组键,然后在内存中对它们进行计数。如果您必须支持大量页面,这将表现不佳。
我是 运行 关于 table 的报告,并按两列分组。我想获得结果中的组总数,以便我可以对报告进行分页。但是 .Count() 方法返回第一组中的行数。查询是
return data.GroupBy(x => new { x.Item.Parent.Name, x.Date })
.Select(x => new Item
{
Parent = x.Key.Name,
Date = x.Key.Date,
PredictedSales = x.Sum(y => y.PredictedSales),
RealSales = x.Sum(y => y.ActualSales),
});
.Count() 正在执行以下查询
select cast(count(*) as INT) as col_0_0_
from dbo.[table1] table1
left outer join dbo.[Table2] table2
on table1.Table2Id = table2.Id
and 0 /* @p0 */ = table2.Deleted
left outer join dbo.[Table3] table3
on table2.Table3Id = table3.Id
where table1.Date >= '2017-03-01T00:00:00' /* @p2 */
and table1.Date <= '2017-03-15T00:00:00' /* @p3 */
and (table1.VariancePercentage is not null)
and abs(table1.VariancePercentage * 100 /* @p4 */) <= 5 /* @p5 */
group by table3.Name,
table1.Date
而我想要的是 select TOP(1) COUNT(*) OVER () FROM.
有什么方法可以使用 linq 查询来实现吗?
这是一个已知问题,NH-3154。
您的案例需要从子查询中计数。据我所知,hql does not support it (subqueries are supported only in select
expression or where
conditions), so it will likely not be supported soon. (linq-to-nhibernate translates to hql.)
因此您必须使用 sql 本机查询进行计数 (session.CreateSQLQuery("...")
),或者在功能和性能上做出一些妥协:
- 选择可供浏览的最大页数。
- 发出以下查询:
var maxResults = maxPageCount * pageSize + 1;
var count = data.GroupBy(x => new { x.Item.Parent.Name, x.Date })
.Select(x => x.Key)
.Take(maxResults)
.ToList()
.Count();
- 如果
count == maxResults
,您可以告诉您的用户还有更多页面。
当然,这将发出一个查询,加载所有分组键,然后在内存中对它们进行计数。如果您必须支持大量页面,这将表现不佳。