join,group by和count sql to linq conversion

时间:2017-04-01 15:16:44

标签: sql linq linq-to-sql asp.net-mvc-5

查询:

SELECT COUNT(*) as Avalied
FROM LeaveMaster as lm
JOIN LeaveSubsidary as ls 
ON lm.TransMasterId = ls.TransMasterId
WHERE lm.SystemCode = 'abc123' AND lm.EmployeeCode = '0014' AND lm.Status ='Approved'
Group by ls.Leave_Type

如何将上述sql查询转换为linq?谢谢:))

编辑:

from p in db.PY_LeaveTransactionMasterTAB.AsEnumerable()
join e in db.PY_LeaveTransactionSubsidaryTAB.AsEnumerable() on p.LV_TransMasterId equals e.LV_TransMasterId into grp
where p.SystemCode == SysCode && p.EmployeeCode == EmpCode && p.Status == "Approved"
group grp by e.Leave_Type // This line is invalid Why?

以上是我到目前为止所尝试的内容,为什么我不能e.Leave_Type或者group grp by e.Leave_Type的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

(from p in db.PY_LeaveTransactionMasterTAB
join e in db.PY_LeaveTransactionSubsidaryTAB on p.LV_TransMasterId equals e.LV_TransMasterId 
where p.SystemCode == SysCode && p.EmployeeCode == EmpCode && p.Status == "Approved"
group new {p,e} by new {e.Leave_Type } into gr
select new 
{
   Leave_Type = gr.Key.Leave_Type ,
   Count = gr.Count()
}).ToList();