使用Entity Framework的前5个具有组的LINQ查询 [英] Top 5 LINQ query with group by using Entity Framework
本文介绍了使用Entity Framework的前5个具有组的LINQ查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用实体框架对前5个LINQ查询进行分组,而下面是sql查询,就像我需要LINQ查询一样.
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
这是我在SQL Server中的表结构:
This is my table structure in SQL Server:
这是我的操作方法,我需要一个linq查询才能将列表返回到我的视图:
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);
}
这是我的模型课:
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";
}
}
预先感谢您的努力.
推荐答案
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();
这篇关于使用Entity Framework的前5个具有组的LINQ查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文