Search code examples
linqfluent-nhibernate

How to select the least count of items in fluent nHibernate via a linq query?


So I got a fluent nHibernate table like this:

public class AnsweredQuestionDb
{
    public virtual long Id { get; set; }
    public virtual QuestionDb Question { get; set; }
    public virtual AnswerDb Answer { get; set; }

}

QuestionDb and AnswerDb are other fluent nHibernate tables.

So I want to select the least answered Question. So if Question A was ansered 3 times and Question B,C and D where answerd 4 times the result should be Question A.

This is the point i am actually working with:

var leastAnswerdQuestion = (from t in m_dbSession.Query<AnsweredQuestionDb>()
                            group t.Id by t.Question into groups
                            select groups.ToList().Sum()).ToList()[0];

but this throws an exception and has no or order by inside. Is this even possible to do in one query?

I hope it is clear what I want to do.

I assume in sql this will look like this:

SELECT Question_id, count(Question_id)
FROM AnsweredQuestionDb
GROUP BY Question_id
ORDER By count(Question_id)

Solution

  • So with the help of Svyatoslav Danyliv I created this:

    Of course this is not perfect but it serves the purpurse:

    QuestionDb nextQuestion = null;
    var grouped =  (from t in m_dbSession.Query<AnsweredQuestionDb>()
                   group t by t.Question.Id into g
                   orderby g.Count()
                   select new
                   {
                       QuestionId = g.Key,
                       Count = g.Count()
                   }).ToList();
    
    var keys = grouped.Select(o => o.QuestionId).ToList();
    var notAnswered = (from t in m_dbSession.Query<QuestionDb>()
                       where 
                       !keys.Contains(t.Id)
                       select t).ToList().First();
    
    if (notAnswered != null)
    {
        nextQuestion = notAnswered;
    }
    else
    {
        if (grouped.Count() == 0)
        {
            nextQuestion = (from t in m_dbSession.Query<QuestionDb>()
                            select t).ToList().First();
        }
        else
        {
            var leastAnsweredId = grouped
                .OrderBy(x => x.Count)
                .Select(x => x.QuestionId)
                .FirstOrDefault();
    
            nextQuestion = (from t in m_dbSession.Query<QuestionDb>()
                            where t.Id == leastAnsweredId
                            select t).ToList().FirstOrDefault();
        }
    }