NHibernate correlated subquery fetching single item

丶灬走出姿态 提交于 2019-12-24 09:35:59

问题


I'm using NHibernate 3.2 and have the following model:

class User
{
    public virtual int Id { get; set; }
    public virtual string Username { get; set; }
    public virtual IList<Log> Logs { get; set; }
}

class Log
{
    public virtual int Id { get; set; }
    public virtual User User { get; set; }
    public virtual DateTime Date { get; set; }
}

Now, I want to query User with the date of ther latest Log-entry.

class UserDto
{
    public int UserId { get; set; }
    public string Username { get; set; }
    public DateTime? LastLogDate { get; set; }
}



What is the most effective way to do this query using NHibernate QueryOver or Linq?

This is the SQL-query I'd like to prodcue:

SELECT u.Id as UserId,
       u.Username as Username,
       (SELECT TOP 1 l.Date
        FROM   [Userlog] l
        WHERE  l.User_id = u.Id) as LastLogDate
FROM   [User] u

回答1:


you could do the same thing with an aggregate query...

Log logAlias = null;
UserDto dto = null;

Session.QueryOver<User>()
    .Left.JoinAlias(x => x.Logs, () => logAlias)
    .SelectList(list => list
        .SelectGroup(x => x.Id).WithAlias(() => dto.UserId)
        .SelectGroup(x => x.Username).WithAlias(() => dto.Username)
        .SelectMax(() => logAlias.Date).WithAlias(() => dto.LastLogDate))
    .TransformUsing(Transformers.AliasToBean<UserDTO>()
    .List<UserDTO>();

or with subquery...

User userAlias = null;
UserDto dto = null;

Session.QueryOver<User>(() => userAlias)
    .SelectList(list => list
        .Select(x => x.Id).WithAlias(() => dto.UserId)
        .Select(x => x.Username).WithAlias(() => dto.Username)
        .SelectSubQuery(QueryOver.Of<Log>()
            .Where(x => x.User.Id == userAlias.Id)
            .OrderBy(x => x.Date).Desc
            .Select(x => x.Date)
            .Take(1)).WithAlias(() => dto.LastLogDate))
    .TransformUsing(Transformers.AliasToBean<UserDTO>()
    .List<UserDTO>();


来源:https://stackoverflow.com/questions/8143468/nhibernate-correlated-subquery-fetching-single-item

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