2012-07-12 102 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