how to get int by using Linq group by DATEPART month in C#

144 Views Asked by At

I have a StayDormApplications table , I have a SQL as below ,

var systemFilesItem = _db.StayDormApplications.Single(r => r.Id == dormapplication.Id);
string SQL = "SELECT  sum(days) days from StayDormApplications where poster = '" + LoginAccount + "' and DATEPART(MONTH, Sdate) = '"+ month_name + "' group by DATEPART(MONTH, Sdate);"; // 

how to convert the SQL with (c#) LINQ?

1

There are 1 best solutions below

0
D-Shih On

You can try to use SqlFunctions.DatePart to make it, otherwise, your query seems don't need to use group by becuase you filter it on the condition.

var systemFilesItem = _db.StayDormApplications
                          .Where(x=> x.poster == LoginAccount && SqlFunctions.DatePart("MONTH", x.Sdate).Value == month_name)
                          .Sum(x=> x.days);