Criteria API - How to get records based on collection count?
- by Cosmo
Hello Guys!
I have a Question class in ActiveRecord with following fields:
[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; }
}
}
How do I write a DetachedCriteria query to get all Questions that have at least 5 related questions (count) in the RelatedQuestions collection?
For now this gives me strange results:
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);
Any ideas what I'm doing wrong?