使用Entity Framework的前5个具有组的LINQ查询

时间:2018-08-03 15:56:14

标签: c# asp.net linq razor

我需要使用实体框架对前5个LINQ查询进行分组,而下面是需要LINQ查询的sql查询。

select top 5 
    EventId,
    Datename(day, EventDate) as Day, 
    convert(varchar(3), EventDate, 100) as Month,  
    Datename(yy, EventDate) as year,
    Title, Description, ThumbImage  
from 
    EventGalleries 
group by 
    EventId, Title, EventDate, Description, ThumbImage 
order by 
    EventDate desc

这是我在SQL Server中的表结构:

enter image description here

这是我的操作方法,我需要一个linq查询才能将列表返回到我的视图:

public ActionResult Gellery()
{
        var list = db.EventGallerys.ToList();// i need linq query here in place of this list
        return View(list);
}

这是我的模型课:

public class EventGallery
{
    [Key]
    public int Sno {get;set;}
    public string ImageName { get; set; }
    public string ThumbImage { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public DateTime EventDate { get; set; }    
    public string EventId { get; set; }
    public string GalleryType { get; set; }  
    public string IP { get; set; }
    public string SubmittedBy { get; set; }
    public DateTime GalleryCreatedDate { get; set; }
    public string Status { get; set; }
   //  Sno,ImageName,ThumbImage,Title,Description,EventDate,GalleryCreatedDate,EventId,GalleryType,Status

    public EventGallery()
    {
        GalleryCreatedDate = DateTime.Now;
        Status = "Active";
    }
}

预先感谢您的努力。

1 个答案:

答案 0 :(得分:0)

db.EventGallerys
  .GroupBy(eg => new { eg.EventId, eg.Title, eg.EventDate, eg.Description, eg.ThumbImage })
  .OrderByDescending(eg => eg.Key.EventDate)
  .Take(5)
  .AsEnumerable()
  .Select(eg => new {
      EventId = eg.Key.EventId,
      Day = eg.Key.EventDate.ToString("D"), 
      Month = eg.Key.EventDate.ToString("MMM"),  
      Year = eg.Key.EventDate.ToString("yyyy"),
      Title = eg.Key.Title, 
      Description = eg.Key.Description,
      ThumbImage = eg.Key.ThumbImage 
   })
  .ToList();