基于 child 集合计数的 Nhibernate queryover 过滤器

Nhibernate queryover filter based on count of child collection

最终我想过滤所有 parent objects 少于 2 children.

我正在构建一个带有网格仪表板的搜索屏幕,它使用以下逻辑作为如何构建查询的示例。

var query = Session.QueryOver<Parent>(() => parentAlias);

if (!string.IsNullOrWhiteSpace(SearchCriteria.OpenedBy))
    query.Where(Restrictions.Eq(Projections.Property<Parent>(x => x.OpenedBy), SearchCriteria.OpenedBy));

if (SearchCriteria.OpenedDateStart != null)
    query.Where(Restrictions.Ge(Projections.Property<Parent>(x => x.OpenedAt), SearchCriteria.OpenedDateStart));

到目前为止,它一直运行良好:

if (!string.IsNullOrEmpty(SearchCriteria.ChildrenAffected) && SearchCriteria.ChildrenAffected == "Multi")
    query.Where(() => parentAlias.Children.Count > 2);

.Count 不起作用是有道理的,这不是真正的 linq。 .Count() 也会抛出错误。老实说,我觉得我已经尝试了所有我能想到的 Restritions、JoinAlias 等的组合,但很久以前我就偏离了有根据的尝试的道路,进入了疯狂猜测的领域。

如何设置查询以根据 QueryOver 语法中 children 的计数过滤掉 parent?

-----注意----- 在 id 获得我的列表后,我讨论过使用 linq,但我在查询设置中进行分页,以便在页面返回后应用过滤器。

你需要一个子查询...

Children childrenAlias = null;
var subquery = QueryOver.Of<Children>(() => childrenAlias)
     .Where(() => childrenAlias.Parent.ID == parentAlias.ID)
     .ToRowCountQuery();
query.WithSubquery.WhereValue(2).Le(subquery);

请注意,我不知道如何做 Count > 2,所以我正在做 2 <= Count,并且有可能

.Where(() => childrenAlias.Parent.ID == parentAlias.ID)

你可以写

.Where(() => childrenAlias.Parent == parentAlias)

嗯...如果你真的需要 Count > 2 你应该能够:

query.Where(Restrictions.Gt(Projections.SubQuery(subquery), 2));

query.WithSubquery.Where(() => subquery.As<int>() > 4);

(这个我没用过...取自http://blog.andrewawhitaker.com/blog/2014/10/24/queryover-series-part-8-working-with-subqueries/