实体框架查询DateTime
本文关键字:DateTime 查询 框架 实体 | 更新日期: 2023-09-27 18:06:00
我想在一个时间跨度内使用实体框架查询获得5个流行故事,例如在7天或14天。我将视图存储在一个单独的表中,其中DateTime
参数与StoryID
。
Stories
表:
StoryID Story
--------------------
1 story one
2 story two
3 story three
4 story four
5 story five
6 story six
Views
table:
ViewID ViewDate StoryID
---------------------------------------
1 2015 07 17 19:00:00 1
2 2015 07 17 20:00:00 1
3 2015 07 17 21:00:00 2
4 2015 07 18 19:00:00 2
5 2015 07 19 19:00:00 2
6 2015 07 21 19:00:00 1
7 2015 07 23 19:00:00 2
编辑:(到目前为止这是我认为我应该怎么做)
return _viewdb.ObjectSet.Where(p => v.ViewDate >= DateTime.Now.AddDays(-14)).Select(p => new ExampleViewModel
{
StoryTitle = p.Sotries.Story,
}).Take(5);
但是这个解决方案将从过去14天获得5个故事视图,我想返回5个storyid的最查看的故事。
请帮
您应该在查询中使用GroupBy
List<string> returnValue = entity.Populars.Join ( entity.Stories, p => p.StoryID, s => s.StoryID, ( p, s ) => new { p = p, s = s } )
.Where ( a => a.p.Date >= DateTime.Now.AddDays ( -14 ) )
.GroupBy ( b => b.s.StoryTitle, b => b.p.Date, ( i, h ) => new { StoryTitle = i, hits = h.Count ( ) } )
.OrderByDescending ( c => c.hits ).Take ( 5 ).Select ( d => d.StoryTitle ).ToList ( )