【问题标题】:SQL Query to LINQ C# [Joining multiple table]SQL 查询到 LINQ C# [加入多个表]
【发布时间】:2016-07-12 08:16:21
【问题描述】:

我正在我的 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}

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

【问题讨论】:

    标签: c# sql-server database linq


    【解决方案1】:

    试试这个

    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

    【讨论】:

    • 我试过了,它奏效了。非常感谢您,先生!干杯!
    【解决方案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 }
    

    【讨论】:

    • @Hebele 的回答 stackoverflow.com/a/38323556/2630427 是正确的人
    • 是的!谢谢你,先生!这确实是一个例子。但是,我无法标记两个正确答案。无论如何,再次感谢您,先生,干杯!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-01
    • 2022-01-19
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 2017-02-03
    • 2011-09-02
    相关资源
    最近更新 更多