2012-10-04 98 views
6

我正在將SQL查詢轉換爲LINQ,該LINQ使用1對1映射創建左連接,並且必須位於方法語法中。我一直在拉我的頭髮,試圖完成這個沒有面紗。我可以在Lambda語法中做到這一點。下面是我試圖運行的示例查詢。他們不是實際的代碼。有人會指出我做錯了什麼嗎?使用方法語法LINQ中的JOIN和LEFT JOIN等效

SQL:

SELECT item.*, item_status.* 
FROM item 
LEFT JOIN item_status 
    ON item.ID = item_status.itemID 
    AND item_status.FLAGGED = true 
WHERE item.published_date > "2008-06-19" 

LINQ:

var linq_query = (
    from selected_item in item 
    join selected_item_status in item_status 
     on selected_item.ID equals item_status.itemID into joined 
    from item_status in joined.DefaultIfEmpty() 
    where item_status.FLAGGED = true 
    select new {selected_item, selected_item_status}).ToList(); 
+0

如果你的代碼實際上不是代碼,我們如何告訴你代碼有什麼問題?我們是否也可以看到「Item」,「item_status」類以及您將匿名類型列表放入的類? –

回答

8

join ... into成爲GroupJoin和第二from成爲SelectMany

var linq_query = Item 
    .GroupJoin(
     item_status.Where(x => x.selected_item_status.FLAGGED), // EDIT: Where clause moved here. 
     selected_item => selected_item.ID, 
     selected_item_status => selected_item_status.itemID, 
     (selected_item, joined) => new 
     { 
      selected_item, 
      statuses = joined.DefaultWithEmpty(), 
     }) 
    .SelectMany(x => x.statuses.Select(selected_item_status => new 
    { 
     x.selected_item, 
     selected_item_status, 
    })) 
    // EDIT: Removed where clause. 
    .ToList(); 

它看起來像Where使左不需要外連接,如同n無論如何,你的狀態將被過濾掉。

編輯:不,在審查SQL時,它看起來像你的LINQ查詢有點不正確。它應該是:

var linq_query = (
    from selected_item in item 
    join selected_item_status 
     in (
      from status in item_status 
      where status.FLAGGED 
      select status) 
     on selected_item.ID equals item_status.itemID into joined 
    from item_status in joined.DefaultIfEmpty() 
    select new {selected_item, selected_item_status}).ToList(); 
+0

謝謝!我從來沒有想到在那裏有連接表上的where子句。 – s1300045

+0

非常感謝 - 我剛剛得到了這個答案,這就是Iw所期待的。正如我想的那樣,將where子句放在與SQl相比更類似於非Method語法linq的地方。 – EGP