Criteria API - 如何根据收集计数获取记录?

时间:2010-05-22 01:50:43

标签: nhibernate hibernate activerecord criteria castle-activerecord

我在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);

任何想法我做错了什么?

1 个答案:

答案 0 :(得分:2)

尝试类似:

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);