【问题标题】:Linq returning different result than SQLLinq 返回的结果与 SQL 不同
【发布时间】:2014-12-18 22:49:59
【问题描述】:

我正在运行这个 Linq 查询:

        var patientList = from p in db.Patients
                          where p.ClinicId==11
            select p.Id;
        var patientswithplan = from p in db.Plans
            where patientList.Contains(p.PatientId)
            select p;

它返回 1030 个结果。

但是当我想出这个查询时,我首先用 sql 编写它来测试它,这会显示 956 个结果

select id from patients where clinicid=11 
and id in(select patientid from plans)  
order by id

我以为这些查询是一样的,有什么区别,哪个是正确的?

【问题讨论】:

  • 第一个从db.Plans中选择,第二个从db.Patients中选择。
  • 有什么区别?是否有重复的结果,或者只是在 C# 中而不是在 SQL 中检索的记录?

标签: c# asp.net linq linq-to-sql


【解决方案1】:

我已经写了一些代码,你可以自己看到区别

void Main()
{
    var Plans = new List<Plan>();
    Plans.Add(new Plan() {PatientId = 1, PlanName = "Good Plan"});
    Plans.Add(new Plan() {PatientId = 2, PlanName = "Bad Plan"});
    var Patients = new List<Patient>();
    Patients.Add(new Patient() {ClinicId = 1, Name = "Frank"});
    Patients.Add(new Patient() {ClinicId = 2, Name = "Fort"});

   // This is your LINQ     
   var patientList = from p in Patients
                     where p.ClinicId == 1
       select p.ClinicId;
   var patientswithplan = from p in Plans
       where patientList.Contains(p.PatientId)
       select p;
   Console.WriteLine(patientswithplan);
   // We return a PLAN here
   // Result
   // IEnumerable<Plan> (1 item) 
   // PatientId 1
   // PlanName  Good Plan

   // This is the equivalent Linq of your SQL    
   var myPatient = Patients.Where(
                           pa => pa.ClinicId == 1 && 
                           Plans.Any(pl => pl.PatientId == pa.ClinicId)
                                 );
   Console.WriteLine(myPatient);
   // Look! We return a PATIENT here
   // Result
   // IEnumerable<Patient> (1 item) 
   // ClinicId  1
   // Name      Frank
}

// Define other methods and classes here
class Patient
{
    public Patient() {}
    public int ClinicId { get; set; }
    public string Name { get; set; }
}

class Plan
{
   public Plan() {}
   public int PatientId { get; set; }
   public string PlanName { get; set; }   
}

【讨论】:

    【解决方案2】:

    查询做了两个不同的事情:

    1) 第一个查询基本上是首先获取患者列表,然后获取计划(您选择“从 db.Plans 中的 p”),将这些选定的患者包含在患者列表中。

    2) 第二个查询是过滤和获取给定诊所的患者,确保这些患者存在于某些计划中。

    因此,结果的数量当然会有所不同,因为患者和计划表中的行数可能不同。

    【讨论】:

      猜你喜欢
      • 2018-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-22
      相关资源
      最近更新 更多