Вопрос

I need to find all the doctors whom have not seen a patient. I have the tables: Doctor, Patient and DrPatientXref. I have the working SQL query but I can't figure out how to make this a Linq to SQL query.

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)

This was my crack at it (it's painfully wrong):

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;

The solution changes the variable "results". Here it is:

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();
Это было полезно?

Решение

The most straight forward way to achieve this and other similair queries in Linq is to make use of Linq's set based operations (Except, Intersect, Union, Distinct). Below is an example of putting Except to use within your query.

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

I believe this should do the trick (untested), and simply your code in the process.

Другие советы

Try this:

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();
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top