将SQL左连接转换为Linq Lambda Expression

时间:2012-07-12 23:20:52

标签: sql linq-to-entities

我有这个SQL查询

select at.description, 
       a.Address1, 
       a.Address2, 
       a.City
  from address_types at
  left join Address a
    on a.addresstype = at.addresstype
    and a.addressid=24

想在Linq Lambda Expression中写出任何线索吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

  var resultset = (from at in addresstypes
                   join a in addresses
                    on at.AddressType equals a.AddressType into joinaddress
                   from ja in joinaddress.DefaultIfEmpty()
                   where (ja != null && ja.AddressID == 24)
                   select new 
                     {
                        AddressType = at.AddressType,
                        AddressID = ja == null ? 0 : ja.AddressID,
                        Address1 = ja== null ? string.Empty : ja.Address1
                      });

答案 1 :(得分:0)

我宁愿按照以下方式简化它

(from at in address_types
join a in address 
on at.addresstype  equals a.addresstype  into tt
from ar in tt.DefaultIfEmpty()
where (ar != null && ar.addressid == 24)
select new 
 {
    at.Description,
    ar.Address1, 
    ar.Address2, 
    ar.City 
  })

我们不需要这个检查“(ja == null)”的原因是因为我们已经在这行“where(ar!= null&& ar.addressid == 24)”中限制了我们的集合。

同时这个查询有效,我的POV是在SQL查询中LEFT JOIN也是多余的。由于你的条件为“a.addressid = 24”,你不会得到NULL行,因此可以将SQL重写为INNER JOIN和LINQ查询以及

(from at in address_types
    join a in address 
    on at.addresstype  equals a.addresstype
    where at.addressid == 24
    select new 
     {
        at.Description,
        a.Address1, 
        a.Address2, 
        a.City  
      })