SQL查询到LINQ C#[加入多个表]

时间:2016-07-12 08:16:21

标签: c# sql-server database linq

我正在我的sql server

中处理此查询
select a.care_type_id, a.description,
isChecked = case when b.care_type_id is null then 'false' else 'true' end
from caretype a
left join patientinsurancetacitem b on a.care_type_id = b.care_type_id and
b.tac_id = 1

我想将查询翻译成LINQ。但是,我遇到了and运营商的问题。到目前为止我有这个代码;

from a in context.CareTypes
join b in context.PatientInsuranceTACItems on a.care_type_id equals
b.care_type_id into x
from xx in x.Where(w => w.tac_id == 1).DefaultIfEmpty()
                   select new { 
                   isChecked = (b.care_type_id == null ? false : true),
                   care_type_id = a.care_type_id,
                   description = a.description}

而且,我也无法获得b变量中等同的isChecked。从哪里开始修改以获得与我的SQL查询相同的结果?在哪里弄错了?

2 个答案:

答案 0 :(得分:5)

试试这个

from a in context.caretype
join b on context.patientinsurancetacitem
      on new { CA = a.care_type_id, CB =  1}  equals
         new { CA = b.care_type_id, CB =  b.tac_id}
      into tmp from b in tmp.DefaultIfEmpty()
select new
{
    care_type_id = a.care_type_id, 
    description = a.description,
    checked = (b != null) // Or ((b == null) ? false : true)
}

同时检查this StackOverflow answer

答案 1 :(得分:2)

关于连接多个列的非常简单的示例是;

from x in entity1
             join y in entity2
             on new { X1= x.field1, X2= x.field2 } equals new { X1=y.field1, X2= y.field2 }