Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 313
topcool Avatar asked Mar 05 '26 06:03

topcool


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.

like image 155
NetMage Avatar answered Mar 07 '26 21:03

NetMage