Entity Framework Core : how can I use DateDiff in Linq?

Viewed 5374

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?

1 Answers

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.

Related