nHibernate投影-分页和不同



我试图解决的高级问题是在搜索子集合中可能存在的东西时消除重复分页。

我采用的方法是创建一个不同的Projection,其中包含与我的DTO相关的信息。我也知道这些值在每一行之间不会改变。

criteria.SetProjection(
Projections.Distinct(Projections.ProjectionList()
.Add(Projections.Alias(Projections.Property("Id"), "Id"))
.Add(Projections.Alias(Projections.Property("Title"), "Title"))
.Add(Projections.Alias(Projections.Property("Firstname"), "Firstname"))
.Add(Projections.Alias(Projections.Property("Surname"), "Surname"))
.Add(Projections.Alias(Projections.Property("DateCreated"), "DateCreated"))));

当我引入分页/排序元素时,就会出现问题。

查看NH Profiler,我看到的SQL类似于:-

SELECT TOP (20 /* @p0 */) y0_,
y1_,
y2_,
y3_,
y4_
FROM   
(
SELECT distinct 
this_.Id as y0_,
this_.Title as y1_,
this_.Firstname as y2_,
this_.Surname as y3_,
this_.DateCreated as y4_,
ROW_NUMBER() 
OVER(ORDER BY this_.Firstname DESC, this_.Surname DESC) 
as __hibernate_sort_row
FROM   Users this_
) as query
WHERE  query.__hibernate_sort_row > 20 /* @p1 */
ORDER  BY query.__hibernate_sort_row;

我想要得到一个DISTINCT投影的意图被挫败了,因为ROW_NUMBER()使每一行都是唯一的。

我看到了这篇博客文章,它描述了我正在经历的同样的问题。

http://www.daczkowski.net/2010/09/07/rows-duplication-for-certain-nhibernate-queries-%E2%80%93-变通方法/

提供的解决方案包括更改nHibernate MS SQL代码;这是一种选择,但我极力避免。在最近版本的nHibernate中是否有解决此问题的选项?

编辑

已在nHibernate 3.3.1中修复-请参阅下面的答案。

为了删除这些重复项,我倾向于在进行分页时将集合属性的提取模式设置为"Select"或"Lazy"(这样,就可以禁用映射的"Eagle"或"Join"提取模式)

假设你有一处房产Children,这将导致删除投影并添加:

criteria.SetFetchMode("Children", FetchMode.Select);

criteria.SetResultTransformer(NHibernate.Transform.Transformers.DistinctRootEntity).List();

经过进一步的研究,我现在找到了一个我满意的解决方案。

据此:-

https://nhibernate.jira.com/browse/NH-2492

该错误已在nHibernate 3.3.1.CR1中得到解决。

我刚刚下载了nHibernate 3.3.1稳定版,并成功地使用了相同的策略,没有重复。

对于那些感兴趣的人,nh3.3.1会抛出以下SQL。

SELECT distinct TOP (20 /* @p0 */) this_.Id as y0_,
this_.Title as y1_,
this_.Firstname       as y2_,
this_.Surname     as y3_,
this_.DateCreated  as y4_,
FROM   Users this_
ORDER  BY this_.Firstname desc,
this_.Surname desc;

最新更新