我需要找到所有没有见过病人的医生。我有桌子:医生,病人和DrPatientXref。我有工作的SQL查询,但我无法弄清楚如何使这成为一个Linq to SQL查询。
select distinct Doctors.FirstName, Doctors.LastName, Doctors.DoctorId
from Doctors, DrPatientXref
where Doctors.DoctorId Not in
(
select DrPatientXref.DoctorId
from DrPatientXref
where DrPatientXref.PatientId = 23)
这是我对它的破解(这是痛苦的错误):
var results = from d in db.Doctors
from x in db.DrPatientXrefs
where
(d.DoctorId == x.DoctorId && x.PatientId != patientId)
select new {
d.DoctorId, d.FirstName, d.LastName
};
var listDrFullName = new List<DoctorFullName>();
foreach (var dr in results) {
DoctorFullName drFullName = new DoctorFullName();
drFullName.FullName = dr.LastName + ", " + dr.FirstName;
drFullName.DoctorId = dr.DoctorId;
listDrFullName.Add(drFullName);
}
return listDrFullName;
解决方案更改变量“results”。这是:
var results = db.Doctors.Except(
(from x in db.DrPatientXrefs
join d in db.Doctors on x.DoctorId equals d.DoctorId
where x.PatientId == patientId // probably not needed...
select d)
).ToList();
答案 0 :(得分:0)
在Linq中实现此问题和其他类似问题的最直接方法是使用Linq的set based operations Except
,Intersect
,Union
,{{1 }})。以下是在查询中使用Distinct
的示例。
Except
我认为这应该可以解决问题(未经测试),并且只需要处理过程中的代码。
答案 1 :(得分:0)
试试这个:
var patientId = 23;
var result = db.Doctors.Where(d => !db.DrPatientXref.Any(x => x.DoctorId == d.DoctorId
&& x.PatientId == patientId))
.Select(d => new { d.FirstName, d.LastName, d.DoctorId } ).ToList();