我在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()
的能力。我们的主持人在这个问题上的帮助不大,我希望有一个解决方法。
答案 0 :(得分: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());
答案 1 :(得分:0)
您可以将日期转换为字符串,并根据日期的字符串表示进行分组。
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
支持。