Linq在内外连接上的难度很大

时间:2015-07-28 19:15:17

标签: c# linq left-join

我无法理解为什么会失败。错误是:

  

失败:标识符' Patient_recid'不是'Nova.Data.Returntooffice'的参数或变量或字段。如果' Patient_recid'是属性请向其添加FieldAlias或Storage属性或将其声明为字段的别名。

是的......这是正确的。表格设置为

  1. Returntooffices引用encountertimes记录(内部联接)。
  2. encountertimes记录引用patient表记录(内连接)。
  3. Returntoooffice记录可能有也可能没有appointment记录 - 这就是我尝试使用左外连接的原因。
  4. returntooffices记录没有patient_recid,这就是我尝试将其加入encountertimes记录的原因。

    这是如何正确完成的?

    TIA

    var query = 
        from rto in cxt.Returntooffices
        from encounter in cxt.Encountertimes.Where(f => f.Recid == rto.Encounter_recid)
        from patient in cxt.Patients.Where(p => p.Recid == encounter.Patient_recid && p.Groupid == groupid)
        from appointment in cxt.Appointments.Where(a => a.Recid == rto.Appointment_recid).DefaultIfEmpty()
        select new
        {
            RTO = rto,
            APPOINTMENT = appointment
         };
    
     var b = query.ToList();
    

1 个答案:

答案 0 :(得分:1)

代替一个更好的主意,这似乎是编译和工作(是啊!)

var q = 
    from rto in cxt.Returntooffices
    join encounter in cxt.Encountertimes on rto.Encounter_recid equals encounter.Recid 
    join patient in cxt.Patients on encounter.Patient_recid equals patient.Recid
    join appointment in cxt.Appointments on rto.Appointment_recid equals appointment.Recid into apt
    from a in apt.DefaultIfEmpty() 
    where patient.Groupid == groupid
    select new
     {
        RTO = rto,
        APPOINTMENT = a
      }
    ).ToList();