How to group by DateTime.Date in EntityFramework(如何在 EntityFramework 中按 DateTime.Date 分组)
问题描述
我有一个设备型号:
public class DeviceModel
{
public DateTime Added { get;set; }
}
我想选择设备计数,按 Added
日期(不是日期和时间,而只有日期)分组.我当前的实现无效,因为 linq 无法将 DateTime.Date
转换为 sql:
And i want to select devices count, grouped by Added
date (not Date and Time, but only date). My current implementation is not valid, because linq can't translate DateTime.Date
to sql:
var result = (
from device in DevicesRepository.GetAll()
group device by new { Date = device.Added.Date } into g
select new
{
Date = g.Key.Date,
Count = g.Count()
}
).OrderBy(nda => nda.Date);
如何更改此查询以使其正常工作?
How to change this query to make it work?
推荐答案
嗯,根据this MSDN 文档,Date
属性受 LINQ to SQL 支持,我假设 Entity Framework 也支持它.
Well, according to this MSDN document, Date
property is supported by LINQ to SQL and I'd assume that Entity Framework supports it as well.
不管怎样,试试这个查询(注意我正在使用 TruncateTime 方法以避免重复解析日期):
Anyway, try this query (notice that I'm using TruncateTime method in order to avoid resolving the date repeatedly):
var result = from device in
(
from d in DevicesRepository.GetAll()
select new
{
Device = d,
AddedDate = EntityFunctions.TruncateTime(d.Added)
}
)
orderby device.AddedDate
group device by device.AddedDate into g
select new
{
Date = g.Key,
Count = g.Count()
};
希望这会有所帮助.
这篇关于如何在 EntityFramework 中按 DateTime.Date 分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 EntityFramework 中按 DateTime.Date 分组


基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01