如何将我的sql代码转换为Linq格式:
我们如何使用Linq c#:
执行选择到另一个选择我的sql代码:
SELECT DepartementProjects.Label, a.Number FROM
(SELECT DepartementProjects.Label ,count(1) as Number FROM DepartementProjects
inner join Absences on DepartementProjects.Id = Absences.DepartementProjectID
where Absences.Profil='SHT'
group by DepartementProjects.Label ) a right join DepartementProjects on DepartementProjects.Label = a.Label;
我的尝试:
var AbsByDepartmentADM = from department in _dbContext.DepartementProjects
join abs in _dbContext.Absences on department.Id equals abs.DepartementProjectID
into groupedResult
from groupedResultRight in groupedResult.DefaultIfEmpty()
group groupedResultRight by department.Label into grouped
let NumberOfAbsence = grouped.Count(t => t.DepartementProjectID != null)
let WorkedHours = grouped.Sum(a => a.WorkedHours != null ? a.WorkedHours : 0)
select new
{
DepartmentId = grouped.Key,
NumberOfAbsence,
WorkedHours,
AbsencesHours = (8 * NumberOfAbsence - WorkedHours),
};
答案 0 :(得分:1)
如果您正在尝试翻译SQL,请首先翻译所有子选择,然后翻译主选择,然后翻译LINQ短语顺序。此外,您的LINQ添加了一些不在SQL中的值,因此我没有尝试更改SQL以匹配:
var sub = from dept in _dbContext.DepartementProjects
join abs in _dbContext.Absences on dept.Id equals abs.DepartementProjectID into absj
from abs in absj
where abs.Profil == "SHT"
group abs by dept.Label into absg
select new { Label = absg.Key, Number = absg.Count() };
var ans = from dept in _dbContext.DepartementProjects
join a in sub on dept.Label equals a.Label into lnj
from ln in lnj.DefaultIfEmpty()
select new { dept.Label, ln.Number };