【问题标题】:Convert this query to Linq to SQL将此查询转换为 Linq to SQL
【发布时间】:2013-10-01 00:04:58
【问题描述】:

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

【问题讨论】:

    标签: sql linq linq-to-sql sql-to-linq-conversion


    【解决方案1】:

    在 Linq 中实现此查询和其他类似查询的最直接方法是使用 Linq 的 set based operationsExceptIntersectUnionDistinct)。下面是在查询中使用 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();
    

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

    【讨论】:

    • 就是这样。只需稍加调整,这里就是: var results = db.Doctors.Except( (from x in db.DrPatientXrefs join d in db.Doctors on x.DoctorId 等于 d.DoctorId where x.PatientId == patientId // 可能不需要... select d) ).ToList();
    【解决方案2】:

    试试这个:

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

    【讨论】:

    • 这会产生:“DrPatientXref”不包含“任何”的定义。有其他选择吗?
    • 我想我忘了添加 db.,应该是 db.DrPatientXref。答案已编辑。
    猜你喜欢
    • 2012-10-11
    • 2017-10-06
    • 2020-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多