【问题标题】:Grouping by day in LINQ without TruncateTime()在没有 TruncateTime() 的 LINQ 中按天分组
【发布时间】:2017-10-04 15:08:42
【问题描述】:

我在 C# Razor MVC 项目中对 MySQL 数据库进行了以下 LINQ 查询。

private Dictionary<DateTime?, int> getOrderQuantityDict(DateTime start, DateTime end, int siteCode)
{
    return (from o in thisDataEntities.this_table
        where o.created_at >= start
        && o.created_at <= end
        && o.store_id == siteCode
        select new { OrderDate = o.created_at, Id = o.entity_id})
        .GroupBy(q => q.OrderDate)
        .ToDictionary(q => q.Key, q => q.Count());
}

我需要按天分组。现在 q.OrderDate 有小时、分钟和秒。我需要在分组时忽略这些。

棘手的部分:我需要在没有TruncateTime() 的情况下执行此操作。当我们的主机移动我们的数据库时,由于某种原因,我们失去了使用TruncateTime() 的能力。我们的主机在这个问题上帮助不大,我希望有一个解决方法。

【问题讨论】:

  • 你可以试试:.GroupBy(q =&gt; q.OrderDate.Date)
  • @JeroenvanLangen - 我担心 Linq to Entities 将无法将属性 .Date 转换为 SQL

标签: c# mysql asp.net-mvc linq razor


【解决方案1】:

尚未对其进行测试,但以下内容可能会对您有所帮助:

return (from o in thisDataEntities.this_table
    where o.created_at >= start
    && o.created_at <= end
    && o.store_id == siteCode
    select new { OrderDate = o.created_at, Id = o.entity_id})
    .AsEnumerable() //Once this is executed, the database will return the result of the query and any other statement after this will be ran locally so TruncateTime will not be an issue
    .GroupBy(q => q.OrderDate)
    .ToDictionary(q => q.Key, q => q.Count());

【讨论】:

  • 有一些小细节错误,但使用.AsEnumerable() 让我运行C# 逻辑的想法绝对是关键。我会建议与我使用的内容相匹配的编辑。非常感谢!
【解决方案2】:

您可以将日期转换为字符串,并根据日期的字符串表示进行分组。

return 
    thisDataEntities.this_table
                    .Where(o => o.created_at >= start)
                    .Where(o => o.created_at <= end)
                    .Where(o => o.store_id == siteCode)
                    .Select(o => new
                            {
                                OrderDate = o.created_at, 
                                Id = o.entity_id,
                                OrderDateFormatted = 
                                    SqlFunctions.DateName("yyyy", o.created_at) + "-" +
                                    SqlFunctions.DateName("mm", o.created_at) + "-" +
                                    SqlFunctions.DateName("dd", o.created_at)
                            })
                    .GroupBy(n => n.OrderDateFormatted) // format "2017-10-03"
                    .ToDictionary(g => g.First().OrderDate, g => g.Count());

以上方法的执行应该发生在数据库端。当然只有在支持GroupBy的情况下。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    • 1970-01-01
    相关资源
    最近更新 更多