2012-07-12 62 views
1

我有这样的SQL查询转换SQL左连接到LINQ Lambda表达式

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表达式,任何线索?

谢谢!

+0

从MSDN一些想法得到空行。 com/en-us/library/bb397895.aspx – 2012-07-13 08:45:56

回答

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) “是因为我们已经在这一行限制了我们的设置”(ar!= null & & ar.addressid == 24)“。

同时这个查询的工作原理,我的POV是,在SQL查询中,LEFT JOIN也是冗余的。 http://msdn.microsoft:你会不会因为你的条件“a.addressid = 24”,所以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 
     }) 
+0

很好的回答!非常感谢 – VAAA 2012-07-13 16:05:12

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 
         }); 
+0

我认为“ja == null?0 ...”是多余的,因为您已经添加了条件“where(ja!= null && ja.AddressID == 24)” – Madman 2012-07-13 10:25:07

+0

@马德曼:是的,在这种情况下,这是多余的。但是,如果我们要执行真正的左连接(显示连接条件不匹配的右列表中的空白值),我们将需要这些检查。让我知道你的想法。 – 2012-07-13 12:42:42