【问题标题】:Criteria API - How to get records based on collection count?Criteria API - 如何根据收集计数获取记录?
【发布时间】:2026-01-19 22:25:01
【问题描述】:

我在 ActiveRecord 中有一个 Question 类,包含以下字段:

[ActiveRecord("`Question`")]
public class Question : ObcykaniDb<Question> {

    private long id;
    private IList<Question> relatedQuestions;

    [PrimaryKey("`Id`")]
    private long Id {
        get { return this.id; }
        set { this.id = value; }
    }

    [HasAndBelongsToMany(typeof(Question), ColumnRef = "ChildId", ColumnKey = "ParentId", Table = "RelatedQuestion")] 
    private IList<Question> RelatedQuestions {
        get { return this.relatedQuestions; }
        set { this.relatedQuestions = value; }
    }
}

如何编写 DetachedCriteria 查询以获取在 RelatedQuestions 集合中至少有 5 个相关问题(计数)的所有问题?

现在这给了我奇怪的结果:

DetachedCriteria dCriteria = DetachedCriteria.For<Question>()
            .CreateCriteria("RelatedQuestions")
            .SetProjection(Projections.Count("Id"))
            .Add(Restrictions.EqProperty(Projections.Id(), "alias.Id"));

DetachedCriteria dc = DetachedCriteria.For<Question>("alias").Add(Subqueries.Le(5, dCriteria));
IList<Question> results = Question.FindAll(dc);

任何想法我做错了什么?

【问题讨论】:

    标签: nhibernate hibernate activerecord criteria castle-activerecord


    【解决方案1】:

    尝试类似:

    var dc = DetachedCriteria.For<Question>()
        .SetProjection(Projections.ProjectionList()
                           .Add(Projections.GroupProperty("Id")))
        .Add(Restrictions.Ge(Projections.Count("RelatedQuestions"), 5))
        .SetResultTransformer(new AliasToBeanResultTransformer(typeof(Question)));
    var questions = Question.FindAll(dc);
    

    【讨论】:

    • 谢谢 Mauricio,我的数据库中有三个问题,其中两个分配了相关问题。现在,您的解决方案在大多数情况下为我提供了三个甚至未初始化的 Question 对象 (id#0) :(
    • 这仅适用于我使用 SQL:“select * from Question q where (select COUNT(*) from RelatedQuestion rq where q.Id = rq.ParentId)
    • @Cosmo:在发布之前我确实在类似的模型上尝试过我的解决方案,并且效果很好:code.google.com/p/mausch/source/browse/trunk/LazyTests/…
    最近更新 更多