我有一个请求列表和请求列表。每个请求可以有零个,一个或多个注释。
public class Request
{
public virtual string Id
{ get; protected set; }
public virtual DateTime Date
{ get; set; }
public virtual byte RequestStatusId
{ get; set; }
public virtual Payment Payment
{ get; set; }
public virtual IList<RequestComment> RequestComments
{ get; set; }
}
public class RequestComment
{
public virtual int Id
{ get; protected set; }
public virtual DateTime Date
{ get; set; }
public virtual string CommentText
{ get; set; }
public virtual Request Request
{ get; set; }
public virtual User User
{ get; set; }
}
我正在使用NHibernate.Linq从数据库中获取数据。 当我排序时,例如通过Request Id,它看起来像这样:
var query = _session.Query<Request>()
.Where(r => r.RequestStatusId == requestStatusId)
.OrderBy(r => r.Id)
.Skip(pageNo * pageSize)
.Take(pageSize);
return query.ToFuture().AsQueryable();
当我需要上次评论请求时,我会这样:
public RequestComment GetLastCommentForRequest(string requestId)
{
var query = _session.Query<RequestComment>()
.Where(r => r.Request.Id == requestId)
.OrderByDescending(r => r.Date)
.FirstOrDefault();
return query;
}
现在我需要获取Requests及其最后一条评论(如果存在),并且全部按CommentText排序。我试图在Request查询中执行命令:
.OrderBy(x => x.RequestComments.Where(y => y.Request.Id == x.Id).OrderByDescending(y => y.Date).FirstOrDefault())
但它没有用,而且我收到错误»调用目标引发了异常。«
更新
这没关系,但它没有按最后评论排序,但首先发现:
.OrderBy(r => r.RequestComments.Select(x => x.CommentText).FirstOrDefault())
答案 0 :(得分:1)
这个怎么样:
.OrderBy(x => x.RequestComments
.OrderByDescending(y => y.Date)
.Select(x => x.CommentText)
.FirstOrDefault()
)
更新:
上面的linq似乎转换为查询子查询具有order by子句,这是不允许的。试试这个:
.OrderBy(x => x.RequestComments
.Where(y => y.Date == x.RequestComments.Max(o => o.Date))
.Select(u => u.CommentText)
.FirstOrDefault()
)
答案 1 :(得分:0)
你可以尝试:
.OrderBy(x => x.RequestComments.Select(y => y.Date).DefaultIfEmpty().Max())