9

I want to create a query in EF Core like this :

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

The above query is for T-SQL - how can I create a query in Linq?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
topcool
  • 2,498
  • 7
  • 28
  • 52

1 Answers1

22

Using DbFunctions, accessed via EF.Functions, you can call DateDiffDay:

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

My SQL to LINQ Recipe might help you with some translation issues in the future.

PS: As noted by @B12Toaster, particular EF.Functions methods are provider specific and DataDiffDay is specific to MS SQL Server.

NetMage
  • 26,163
  • 3
  • 34
  • 55
  • 1
    Just a remark: "DateDiffDay() is an SQL Server-specific extension and doesn't work when using Npgsql." – https://github.com/npgsql/efcore.pg/issues/473#issuecomment-404829344 – Felix K. Dec 29 '20 at 15:13
  • 1
    @B12Toaster Yes, that seems to be a difference from EF 6.x where certain functions were required of every provider. I think I would prefer if EF Core also has a base of required translations as the current model makes being agnostic to database engine impossible. – NetMage Dec 29 '20 at 19:07