使用子查询过滤子集合

时间:2017-03-15 08:08:08

标签: c# entity-framework linq-query-syntax

我在sql中有一个查询,如下面的代码所示:

select *
from Registration r
    inner join RegistrationService rs on rs.RegistrationID = r.RegistrationID
    inner join Service s on s.ServiceID = rs.ServiceID
where cast(RegistrationDate as DATE) between @startDate and @endDate
    and s.ByDoctor = 'false'
    and rs.ServiceID not in (select ServiceID from TreatmentService ts where ts.TreatmentID = r.RegistrationID)

现在我必须将其转换为linq语法,因为我使用EF作为我的数据访问。我在转换最后一行时遇到了问题:

rs.ServiceID not in (select ServiceID from TreatmentService ts where ts.TreatmentID = r.RegistrationID)

和我的linq语法:

var query = context.Registrations.Where(r =>
    DbFunctions.TruncateTime(r.RegistrationDate) == DbFunctions.TruncateTime(DateTime.Today)
    &&
    r.RegistrationServices.Any(rs => rs.Service.ByDoctor == false)
    &&
    !(context.TreatmentServices.Select(ts => ts.ServiceID).Where(ts => ts.TreatmentID == r.RegistrationID)).Contains(rs.ServiceID) <-- here is the problem
);

如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

为什么不使用类似linq查询的语法?

from r 
in context.Registration
join rs in context.RegistrationService on rs.RegistrationID = r.RegistrationID
join s in context.Service on  s.ServiceID = rs.ServiceID
...

取自:LINQ query examples

答案 1 :(得分:0)

from r 
in context.Registration
join rs in context.RegistrationService on rs.RegistrationID equals r.RegistrationID
join s in context.Service on  s.ServiceID  equals  rs.ServiceID

where s.Where(ts=>ts.TreatmentID == r.RegistrationID).All(ts => ts.ServiceID  != rs.ServiceID )