【问题标题】:Entity Framework Core : how can I use DateDiff in Linq?实体框架核心:如何在 Linq 中使用 DateDiff?
【发布时间】:2020-10-16 06:28:21
【问题描述】:

我想像这样在 EF Core 中创建一个查询:

SELECT SUM(DATEDIFF(DAY, FromDate, ToDate)) AS Diff 
FROM Table1

以上查询是针对 T-SQL 的 - 我如何在 Linq 中创建查询?

【问题讨论】:

  • 什么版本的 EF(EF 6.x、EF Core 2.0 / 2.x / 3.x)?您将使用 EntityFunctionsDbFunctions DiffDays 方法。
  • @NetMage 我使用的是 EF Core 3.1

标签: sql linq asp.net-core entity-framework-core


【解决方案1】:

使用DbFunctions,通过EF.Functions访问,可以拨打DateDiffDay

var ans = from t in Table1
          group t by 1 into tg
          select tg.Sum(r => EF.Functions.DateDiffDay(r.FromDate, r.ToDate));

我的SQL to LINQ Recipe 将来可能会帮助您解决一些翻译问题。

PS:正如@B12Toaster 所述,特定的EF.Functions 方法是特定于提供程序的,而DataDiffDay 特定于MS SQL Server。

【讨论】:

  • 只是备注:“DateDiffDay() 是 SQL Server 特定的扩展,在使用 Npgsql 时不起作用。” – github.com/npgsql/efcore.pg/issues/473#issuecomment-404829344
  • @B12Toaster 是的,这似乎与 EF 6.x 不同,在 EF 6.x 中,每个提供程序都需要某些功能。我认为如果 EF Core 也具有所需的翻译基础,我会更喜欢,因为当前模型无法与数据库引擎无关。
猜你喜欢
  • 1970-01-01
  • 2020-04-03
  • 1970-01-01
  • 2016-05-31
  • 1970-01-01
  • 2021-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多