【问题标题】:Entity Framework SQL query on DateTimeDateTime 上的实体框架 SQL 查询
【发布时间】:2015-10-23 15:03:53
【问题描述】:

我想在一个时间跨度(例如 7 天或 14 天)内使用 Entity Framework 查询获得 5 个热门故事。我用DateTime 参数和StoryID 将视图存储在一个单独的表中。

Stories表:

StoryID   Story
--------------------
1         story one
2         story two 
3         story three
4         story four
5         story five
6         story six

Views表:

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 个故事 ID 的观看次数最多的故事。

请帮忙

【问题讨论】:

  • 您可能应该向我们提供您的模型和您正在处理的一些业务逻辑,然后我们才能真正为您提供帮助。
  • views.Where(v => v.ViewDate >= DateTime.Now.AddDays(-14) && v.ViewDate <= DateTime.Now.AddDays(-7));怎么样
  • @JDupont:我刚刚更新了我的问题,请再次检查。谢谢
  • @MatiCicero:如何获得过去 14 天内观看次数最多的 5 个 StoryID?

标签: c# sql asp.net-mvc entity-framework asp.net-mvc-5


【解决方案1】:

您应该在查询中使用 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 ( )

【讨论】:

  • 感谢您的帮助。但是如何使用 GroupBy 中的视图表中的外键从故事表中获取一些值,以便我可以获取故事标题并将其传递给视图模型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-03
  • 2012-03-09
相关资源
最近更新 更多