我有这个LINQ查询
var data = (from orders in db.Orders
group orders by orders.OrderDate into dateGroup
select new OrderDateGroup()
{
OrderDate = dateGroup.Key,
OrderCount = dateGroup.Count()
}).Take(10);
orders.OrderDate是DateTime但我想仅根据日期
进行分组答案 0 :(得分:7)
您可以使用规范函数:
group orders by EntityFunctions.TruncateTime(orders.OrderDate) into dateGroup
其他信息:
EntityFunctions
方法称为 规范函数 。这些是一组功能,所有实体框架提供程序都支持这些功能。这些规范函数将转换为提供程序的相应数据源功能。规范函数是访问核心语言之外的功能的首选方法,因为它们可以使查询保持可移植性。
您可以找到所有规范函数here以及所有日期和时间规范函数here。
此外,请不要忘记在System.Data.Objects
中添加System.Data.Entity.dll
名称。
<强> 注意:的强>
如果您使用的是EF6,则必须考虑将EntityFunctions
更改为DbFunctions
。并且不要忘记在System.Data.Entity
中添加EntityFramework.dll
namepsace。
答案 1 :(得分:1)
您可以通过获取DateTime日期来尝试以下代码(我不确定它是否在LINQ to Entities中工作):
var data = (from orders in db.Orders
group orders by orders.OrderDate.Date into dateGroup
select new OrderDateGroup()
{
OrderDate = dateGroup.Key,
OrderCount = dateGroup.Count()
}).Take(10);