Daniel Lang
Daniel Lang

Reputation: 6839

NHibernate correlated subquery fetching single item

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

Upvotes: 1

Views: 1303

Answers (1)

dotjoe
dotjoe

Reputation: 26940

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>();

Upvotes: 3

Related Questions