Please help me write LINQ for this SQL
select svc.SvcName, svcOptions.SvcOptionName, svcMap.Price from svcMap
inner join
svc
on svcMap.SvcId = svc.SvcId
inner join
svcOptions
on svcOptions.SvcOptionId = CASE WHEN (svcMap.DesiredSvcOptionId <> 0 AND svcMap.DesiredSvcOptionId <> svc.DisabledSvcOptionId) THEN
svcMap.DesiredSvcOptionId
WHEN (svcMap.PresentSvcOptionId <> svc.DisabledSvcOptionId) THEN
svcMap.PresentSvcOptionId
ELSE
0
END
where svcMap.ToBill = 1
and
(
(svcMap.DesiredSvcOptionId = 0 AND svcMap.PresentSvcOptionId <> svc.DisabledSvcOptionId)
OR
(svcMap.DesiredSvcOptionId <> 0 AND svcMap.DesiredSvcOptionId <> svc.DisabledSvcOptionId)
)
SOLUTION
This is the solution that I implemented and it gave me exactly what I needed when I cross checked it with LinqPad
from svcMap in db.ServicesMap
join svc in db.Services on svcMap.SvcId equals svc.SvcId
join option in db.Options on
((svcMap.DesiredSvcOptionId != 0 && svcM开发者_StackOverflow中文版ap.DesiredSvcOptionId != svc.DisabledSvcOptionId)
? svcMap.DesiredSvcOptionId
: (svcMap.PresentSvcOptionId != svc.DisabledSvcOptionId)
? svcMap.PresentSvcOptionId
: 0)
equals option.SvcOptionId
where svcMap.ToBill == 1
&& (
(svcMap.DesiredSvcOptionId == 0 &&
svcMap.PresentSvcOptionId != svc.DisabledSvcOptionId)
||
(svcMap.DesiredSvcOptionId != 0 &&
svcMap.DesiredSvcOptionId != svc.DisabledSvcOptionId)
)
select
new
{
svc.SvcName,
option.SvcOptionName,
svcMap.Price.GetValueOrDefault()
}
Why have a CASE in your joining criteria? What do you expect the optimizer to do with that exactly?
Here's a literal translation.
from svcMap in db.svcMaps
where svcMap.ToBill == 1
let svc = svcMap.Svc
where (svcMap.Desired == 0 && svcMap.Present <> svc.Disabled)
|| (svcMap.Desired <> 0 && svcMap.Desired <> svc.Disabled)
let optionId =
svcMap.Desired <> 0 && svcMap.Desired <> svc.Disabled ? svcMap.Desired :
svcMap.Present <> svc.Disabled ? svc.Present :
0
from option in db.Options
where option.SvcOptionId == optionId
select new {svc.SvcName, option.SvcOptionName, svcMap.Price }
精彩评论