views:

55

answers:

1

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?

+2  A: 

Try something like:

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 Scheffer
Thanks Mauricio, I have three Questions in my DB, two of them have related questions assigned. Now, your solution gives me in most cases three Question objects that are even not initialized (id#0) :(
Cosmo
This is working for me using only SQL: "select * from Question q where (select COUNT(*) from RelatedQuestion rq where q.Id = rq.ParentId) < 3". Any idea how to port this?
Cosmo
@Cosmo: I did try my solution on a similar model before posting it, and it worked fine: http://code.google.com/p/mausch/source/browse/trunk/LazyTests/DivisionTests.cs#100
Mauricio Scheffer