2013-09-29 92 views
3

我有一個NoteBrief實體框架 - 通過選擇組,選擇最多的日期

public int Id { get; set; } 
public string Title { get; set; } 
public DateTime Created { get; set; } 
public int ParentNoteId { get; set; } 

數據看起來像

1 Title1 03/31/1987 1 
2 Title1 03/31/1988 1 
3 Title3 01/01/2000 3 
4 Title4 01/01/2001 4 
5 Title4 01/01/2005 4 

我想做的事:現在

SELECT t1.* 
FROM Notes AS t1 LEFT JOIN Notes AS t2 
ON (t1.ParentNoteId = t2.ParentNoteId AND t1.Created < t2.Created) 
WHERE t2.Created IS NULL; 

我有:

public IQueryable<NoteBrief> GetNotes() 
    { 

     return _ctx.Notes.Select(r => new NoteBrief 
     { 
      Id = r.Id, 
      Title = r.Title, 
      Created = r.Created, 
      ParentNoteId = r.ParentNoteId, 
     }); 

    } 

我對此感到滿意,但實際上並不需要parentNoteId的舊版本,只需要最後創建的那個,以便我可以鏈接到它。

我讀過很多例子,其中一些使用FirstOrDefault,一些使用max。每次我嘗試實現一個例子,但它不適合我。

回答

8

Entity Framework creating IQuerable of the most recent

這是最終爲我工作:

 return from e in _ctx.Notes 
       group e by e.ParentNoteId into g 
       select g.OrderByDescending(e => e.Created).FirstOrDefault() into r 
       select new NoteBrief 
       { 
        Id = r.Id, 
        Title = r.Title, 
        Created = r.Created, 
        ParentNoteId = r.ParentNoteId, 
       }; 

還編輯我原來的職位與正確的查詢我去了。

謝謝。

1

嘗試以下

return _ctx.Notes.Select(r => new NoteBrief 
    { 
     Id = r.Id, 
     Title = r.Title, 
     Created = r.Created, 
     ParentNoteId = r.ParentNoteId, 
    }).OrderBy(x=>x.Created).GroupBy(x=>new {Id=x.Id, Title=x.Title}).Select(x=>x.First()).AsQueryable(); 

}