使用子查询过滤子集合
Filtering child collection with subquery
我在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
);
如何解决?
为什么不使用类似 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
...
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 )
我在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
);
如何解决?
为什么不使用类似 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
...
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 )