c# - 如何在 Linq to SQL 中添加日期

标签 c# datetime linq-to-sql

我正在编写这段代码。这里dt被输入到函数中,还有someint。 Exp 列是 T-SQL 日期列,通过 Linq 作为 DateTime 出现。

return (from a in dataContext.TableOfA
       where a.name == "Test" &&
       a.Exp.Value.AddDays(Convert.ToDouble(Someint)) >= new DateTimeOffset(dt)
       select a).First();

在 C# 中,您可以将 double 值添加到日期时间。这意味着您可以增加 1.5 天。在 T-SQL 中,您只能添加 1 天,然后是 12 小时。您必须为每个部分添加一个 int。因此,当 Linq 将 AddDays 转换为 T-SQL 时,它会将我的天数转换为毫秒,并将这些天数相加。这允许它提供 double 为 C# 提供的所有精度。

问题就在这里。当这涉及到 SQL 时,我收到错误:

The datepart millisecond is not supported by date function dateadd for data type date

基本上,您不能将毫秒添加到日期。好吧,别开玩笑了。但是我怎样才能得到在这里翻译的东西呢?我想将 int days 添加到日期。唯一想这样做是为了将他们的负面影响加到我与之比较的另一个人身上吗?如果我想在添加到一列时与列进行比较怎么办?

更新 1

Keith wrote, A command like datepart(millisecond, 10000, myDate) has been supported in T-SQL since at least SQL Server 2000. This error suggests that whatever database you are using does not support the millisecond date part, which seems strange to me.

请注意,我使用的是 SQL Server 2008。DATE 数据类型不支持它。它在日期时间上受支持。

最佳答案

如果您使用 Entity Framework ,请使用 System.Data.Objects.EntityFunctions,如下所示:

c.CMT_TS > System.Data.Objects.EntityFunctions.AddDays(e.Call.CALL_TS, 1)

关于c# - 如何在 Linq to SQL 中添加日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1227648/

相关文章:

c# - Entity Framework Core 2(代码优先)更新值不起作用

C# - 3D 数组的 3D 数组

C#语法问题

date - 如何在sqlite中将字符串日期转换为日期格式

python - 使用 strptime 将字符串转换为带有时区偏移的 python 日期类型对象

c# - Linq-to-SQL 的开销

c# - Linq 相当于 SQL LIKE [a-f]

c# - 你如何制作一个完全方形的按钮?

python - 如何在 Python 中从当年打印明年

c# - 如何学习 LINQ 中的查询