GROUP BY and HAVING clauses in nHibernate QueryOver

吃可爱长大的小学妹 提交于 2019-12-09 16:24:28

问题


I'm trying to write this specific sql query in nHibernate QueryOver language, which I am not very familiar with:

SELECT MessageThreadId FROM MessageThreadAccesses
WHERE ProfileId IN (arr)
GROUP BY MessageThreadId
HAVING COUNT(MessageThreadId) = arr.Count

where arr is a array of integers(user Ids) I'm passing as argument and MessageThreadAccess entity looks like this:

public virtual MessageThread MessageThread { get; set; }
public virtual Profile Profile { get; set; }
....

After reading multiple stack overflow threads and experimenting I got this far with my query (trying to get MessageThread object - it should always be just one or none), but it still doesn't work and I'm not really sure what else to try. The query always seems to be returning the MessageThreadAccess object, but when reading it's MessageThread property it's always NULL.

var access = Session.QueryOver<MessageThreadAccess>()
    .WhereRestrictionOn(x => x.Profile).IsIn(participants.ToArray())
    .Select(Projections.ProjectionList()
        .Add(Projections.Group<MessageThreadAccess>(x => x.MessageThread))
    )
    .Where(
        Restrictions.Eq(Projections.Count<MessageThreadAccess>(x => x.MessageThread.Id), participants.Count)
    )
    .TransformUsing(Transformers.AliasToBean<MessageThreadAccess>())
    .SingleOrDefault();

return Session.QueryOver<MessageThread>()
    .Where(x => x.Id == access.MessageThread.Id)
    .SingleOrDefault();

Can someone point me in the right direction, or explain what am I doing wrong?

Thanks in advance.


回答1:


I guess you may try using a DTO for storing the result, instead of trying to fit the result in a MessageThreadAccess, when it is not one (no Profile).

Maybe you can try :

public class MessageThreadCountDTO
{
    public MessageThread Thread { get; set; }
    public int Nb { get; set; }
}

then

var profiles = new int[] { 1,2,3,4 };

MessageThreadCountDTO mtcDto = null;

var myResult = 
  _laSession.QueryOver<MessageThreadAccess>()
     .WhereRestrictionOn(x => x.Profile.Id).IsIn(profiles)
     .SelectList(list =>
         list.SelectGroup(x => x.MessageThread).WithAlias(() => mtcDto.Thread).
         SelectCount(x => x.MessageThread).WithAlias(() => mtcDto.Nb)
         )
     .Where(Restrictions.Eq(Projections.Count<MessageThreadAccess>(x => x.MessageThread), profiles.Count()))
     .TransformUsing(Transformers.AliasToBean<MessageThreadCountDTO>())
     .List<MessageThreadCountDTO>().FirstOrDefault();

would profiles be a Profile[], and not an int[], then the following line :

.WhereRestrictionOn(x => x.Profile.Id).IsIn(profiles)

should be :

.WhereRestrictionOn(x => x.Profile).IsIn(profiles)

Hope this will help



来源:https://stackoverflow.com/questions/14602005/group-by-and-having-clauses-in-nhibernate-queryover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!