如何将这个普通的sql转换为linq到sql?
select m.Id, m.Name, m.RedLight, m.OrangeLight, m.GreenLight, count(pos.HealthModuleId) as NumberOfBookingsPerDate
from tdHealthModules m
left join (
HealthEventPos pos
join tdHealthEvents e on pos.HealthEventId = e.Id
) on m.Id = pos.HealthModuleId and convert(date,e.Starttime) = CONVERT(DATE,'20180410')
group by m.Id, m.Name, m.RedLight, m.OrangeLight, m.GreenLight
having count(pos.HealthModuleId) < m.RedLight
我实际上已经跟随,这提供了不一样的结果
var m = (from modules in _appContext.HealthModule
join pos in _appContext.HealthEventPos on modules.Id equals pos.HealthModuleId into posGroup
from posItem in posGroup.DefaultIfEmpty(new HealthEventPos { Id = 0, HealthEventId = 0, HealthModuleId = 0 })
join e in _appContext.HealthEvent on posItem.HealthEventId equals e.Id into eventGroup
from eItem in eventGroup.DefaultIfEmpty(new HealthEvent { Id = 0, StartTime = eventDate })
where eItem.StartTime.Date.Equals(eventDate)
group modules by new { modules.Id, modules.Name, modules.RedLight, modules.OrangeLight, modules.GreenLight, count = eventGroup.Count() } into g
where g.Count() < g.Key.RedLight
select new HealthModule
{
Id = g.Key.Id,
Name = g.Key.Name,
RedLight = g.Key.RedLight,
OrangeLight = g.Key.OrangeLight,
GreenLight = g.Key.GreenLight,
NumberOfBookingsPerDate = g.Key.count
});
如何将左连接写入两个内连接表?
答案 0 :(得分:0)
最后,我开始关注两个内部连接表上的左外连接问题的解决方案
var ep = from pos in _appContext.HealthEventPos
join e in _appContext.HealthEvent on pos.HealthEventId equals e.Id
where e.StartTime.Date.Equals(eventDate)
select pos;
一个额外的变量,它包含连接表,然后将用于左连接
var m = (from modules in _appContext.HealthModule
join ePos in ep on modules.Id equals ePos.HealthModuleId into ePosGroup
from ePos in ePosGroup.DefaultIfEmpty(defaultPos)
group new { modules, ePos } by new { modules.Id, modules.Name, modules.Owner, modules.RedLight, modules.OrangeLight, modules.GreenLight } into g
where g.Count(t => t.ePos.HealthModuleId != 0) < g.Key.RedLight
select new HealthModule
{
Id = g.Key.Id,
Name = g.Key.Name,
Owner = g.Key.Owner,
RedLight = g.Key.RedLight,
OrangeLight = g.Key.OrangeLight,
GreenLight = g.Key.GreenLight,
NumberOfBookingsPerDate = g.Count(t => t.ePos.HealthModuleId != 0)
});