0

我需要找到所有没有看过病人的医生。我有表格:Doctor、Patient 和 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;

解决方案更改变量“结果”。这里是:

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();
4

2 回答 2

0

在 Linq 中实现此查询和其他类似查询的最直接方法是利用 Linq 的基于集合的操作( Except, Intersect, Union, Distinct)。Except下面是在查询中使用的示例。

var drdrs = db.Doctors.Except(
  (from x in db.DrPatientXrefs
  join d in db.Doctors on d.DoctorId equals x.DoctorId
  where x.PatientId == patientId // probably not needed...
  select d)
).ToList();

我相信这应该可以解决问题(未经测试),并且只是您在此过程中的代码。

于 2013-10-01T00:15:25.490 回答
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();
于 2013-10-01T00:33:31.280 回答