简体   繁体   中英

Top 5 LINQ query with group by using Entity Framework

I need top 5 LINQ query with group by using entity framework and below is sql query like that i need LINQ query.

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

This is my table structure in SQL Server:

在此处输入图片说明

This is my action method and I need a linq query to return list to my view:

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

This is my model class:

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

Thank you in advance for your effort.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM