My Linq skills are not robust but I usually find answers to most of my questions by “Googling it”.
I’ve been having a hard time trying to create an equivalent Linq statement to the SQL statement below.
I was wondering if anyone had any pointers or is this even possible?
I’m using code and multiple queries to get what I want for now but it would be nice if I could just get this into a Linq statement and iterate through the rows.
SELECT EmpBasic.Company, EmpBasic.EmpID, EmpBasic.Name, LaborDtl.ClockInDate, SUM(LaborDtl.LaborHrs) AS TotalHrs
FROM Erp.LaborDtl
INNER JOIN dbo.EmpBasic ON EmpBasic.Company = LaborDtl.Company AND LaborDtl.EmployeeNum = EmpBasic.EmpID
WHERE EmpBasic.Company = ‘CT’ AND LaborDtl.ClockInDate = ‘4/20/2023’ AND EmpBasic.EmpStatus = ‘A’
GROUP BY EmpBasic.Company, EmpBasic.EmpID, EmpBasic.Name, LaborDtl.ClockInDate
HAVING SUM(LaborDtl.LaborHrs) > 12 OR SUM(LaborDtl.LaborHrs) < 8
string company = "CT";
DateTime clockInDate = DateTime.Parse("4/20/2023");
string empStatus = "A";
var query = from laborDtl in Db.LaborDtl
join empBasic in Db.EmpBasic
on new { laborDtl.Company, EmployeeNum = laborDtl.EmployeeNum }
equals new { empBasic.Company, EmployeeNum = empBasic.EmpID }
where empBasic.Company == company
&& laborDtl.ClockInDate == clockInDate
&& empBasic.EmpStatus == empStatus
group laborDtl by new
{
empBasic.Company,
empBasic.EmpID,
empBasic.Name,
laborDtl.ClockInDate
} into grouped
let totalHrs = grouped.Sum(x => x.LaborHrs)
where totalHrs > 12 || totalHrs < 8
select new
{
grouped.Key.Company,
grouped.Key.EmpID,
grouped.Key.Name,
grouped.Key.ClockInDate,
TotalHrs = totalHrs
};
var result = query.ToList();
Note I didn’t test this thoroughly but it seems to work fine in my LinqPad