title: Order by property of nested object with NHibernate Linq
body: <p>I have class Request with list of Comments. Each Request can have zero, one or many Comments.</p>
  
  <pre><code>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&lt;RequestComment&gt; 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; }
  }
  </code></pre>
  
  <p>I'm using NHibernate.Linq to get data from database.
  When I sort, for example by Request Id, it looks like this:</p>
  
  <pre><code>var query = _session.Query&lt;Request&gt;()
                  .Where(r =&gt; r.RequestStatusId == requestStatusId)
                  .OrderBy(r =&gt; r.Id)
                  .Skip(pageNo * pageSize)
                  .Take(pageSize);
  return query.ToFuture().AsQueryable();
  </code></pre>
  
  <p>When I need last comment for Request I get it like this:</p>
  
  <pre><code>public RequestComment GetLastCommentForRequest(string requestId)
  {
      var query = _session.Query&lt;RequestComment&gt;()
              .Where(r =&gt; r.Request.Id == requestId)
              .OrderByDescending(r =&gt; r.Date)
              .FirstOrDefault();
  
      return query;
  }
  </code></pre>
  
  <p>Now I need to get Requests, with their last comment (if exists) and all sorted by CommentText. I was trying to do order in Request query with:</p>
  
  <pre><code>.OrderBy(x =&gt; x.RequestComments.Where(y =&gt; y.Request.Id == x.Id).OrderByDescending(y =&gt; y.Date).FirstOrDefault())
  </code></pre>
  
  <p>But it's not working and I'm getting error »Exception has been thrown by the target of an invocation.«</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>This is ok, but it's not sorted by last comment, but by first found:</p>
  
  <pre><code>.OrderBy(r =&gt; r.RequestComments.Select(x =&gt; x.CommentText).FirstOrDefault())
  </code></pre>