c# - 如何在 Entity Framework 查询中将 DateTime 转换为 TimeSpan

标签 c# sql-server entity-framework linq

我在 Entity Framework 6 中有这个 LINQ 查询:

var timeCapturesQuery = Context.TimeCaptures
    .Where(t =>
        && t.StartDateTime.TimeOfDay < endTime
        && t.EndDateTime.TimeOfDay > startTime);

EndTime 和 StartTime 是 TimeSpan 类型的参数,StartDateTime 和 EndDateTime 是 datetime 表中的列。

不幸的是,我在运行时遇到了这个错误:

The specified type member 'TimeOfDay' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

如何在此 LINQ 查询中从 DateTime 获取 TimeSpan(即 SQL 中 datetimetime)?

最佳答案

看起来像DbFunctions.CreateTime是你要找的:

When used as part of a LINQ to Entities query, this method invokes the canonical CreateTime EDM function to create a new TimeSpan object.

因此要在两次之间获得结果,您可以:

var timeCapturesQuery = Context.TimeCaptures.Where(t =>
        DbFunctions.CreateTime(t.StartDateTime.Hour, t.StartDateTime.Minute, t.StartDateTime.Second) < endTime &&
        DbFunctions.CreateTime(t.EndDateTime.Hour, t.EndDateTime.Minute, t.EndDateTime.Second) > startTime);

关于c# - 如何在 Entity Framework 查询中将 DateTime 转换为 TimeSpan,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39822588/

相关文章:

c# - Entity Framework 5.0 的数据注释(数据库优先)

c# - 如何确保用户只被添加到列表一次

c# - SqlCommand.StatementCompleted 应该在什么时候触发?

c# - 如何在 c sharp 中的单个 com 端口同时接收多个任务

java - Springboot 2.0无法访问SQL Server数据库

sql-server - 如何将驱动器映射到 SQL 实例?

c# - 在 Entity Framework 中按日期划分实体

c# - 无效方差 : The type parameter must be invariantly valid but is covariant

没有结束日期的 SQL DateDiff

c# - 简单的 Where 子句在 EF5 中停止工作