我正在使用NHibernate 3.2并具有以下模型:
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; }
}
现在,我想用最新的日志条目查询用户。
class UserDto
{
public int UserId { get; set; }
public string Username { get; set; }
public DateTime? LastLogDate { get; set; }
}
使用NHibernate QueryOver或Linq进行此查询的最有效方法是什么?
这是我想要推销的SQL查询:
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
答案 0 :(得分:3)
你可以用聚合查询做同样的事情......
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>();
或子查询...
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>();