Entity Framework - select group by, select max date

前端 未结 2 716
走了就别回头了
走了就别回头了 2021-01-06 14:57

I have a NoteBrief

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


        
相关标签:
2条回答
  • 2021-01-06 15:48

    Entity Framework creating IQuerable of the most recent

    This is what finally worked for me:

            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,
                   };
    

    Also edited my original post with correct query i was going for.

    Thanks.

    0 讨论(0)
  • 2021-01-06 15:50

    Try following

        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();
    

    }

    0 讨论(0)
提交回复
热议问题