实体框架 - 选择分组依据,选择最大日期

时间:2013-09-29 00:20:36

标签: entity-framework

我有一个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。每次我尝试实现一个例子时,它对我来说都不起作用。

2 个答案:

答案 0 :(得分:9)

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 :(得分: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();

}