2009-09-08 108 views
1

此LINQ查詢表達式會發出左的連接和工作原理:LINQ to SQL - 如何將where子句添加到左連接?

from p in Prices 
join ip in ItemPrices 
    on new { p.PriceId, ItemId = 7 } equals 
     new { ip.PriceId, ip.ItemId } 
into priceItemPrice 
from pip in priceItemPrice.DefaultIfEmpty() 
select new 
{ 
    pricesPriceId = p.PriceId, 
    z = (int?)pip.PriceId, 
    p.Content, 
    p.PriceMinQ 
} 

SQL發出:

-- Region Parameters 
DECLARE @p0 Int = 7 
-- EndRegion 
SELECT [t0].[priceId] AS [pricesPriceId], 
    [t1].[priceId] AS [z], 
    [t0].[price] AS [Content], 
    [t0].[priceMinQ] AS [PriceMinQ] 
FROM [price] AS [t0] 
LEFT OUTER JOIN [itemPrice] AS [t1] 
    ON ([t0].[priceId] = [t1].[priceId]) 
    AND (@p0 = [t1].[itemId]) 

我怎樣才能得到它發出下面的SQL?它只是在最後加上了where子句。 where子句不被「pip」所接受,並且在DefaultIfEmpty()之前的lambda表達式不起作用。我知道我可以在選擇過濾出來,但那不是我需要的。

SELECT [t0].[priceId] AS [pricesPriceId], 
    [t1].[priceId] AS [z], 
    [t0].[price] AS [Content], 
    [t0].[priceMinQ] AS [PriceMinQ] 
FROM [price] AS [t0] 
LEFT OUTER JOIN [itemPrice] AS [t1] 
    ON ([t0].[priceId] = [t1].[priceId]) 
    AND (@p0 = [t1].[itemId]) 
WHERE [t1].[priceId] is null 

更新 Oy公司合租的,我的錯誤,where子句做工作 - 由於某種原因,VS2008並沒有表現並給我的悲傷,我的肚子咆哮。我在LinqPad中測試過,where子句很好。所以這一點除了沒有工作:

... 
from pip in priceItemPrice.DefaultIfEmpty() 
*** where pip.ItemId == null *** 
select new 
... 

回答

6

下面是如何OneDotNetWay做過類似的東西樣品。我試圖採取他們的例子,並匹配您的查詢。

var query = p in Prices 
    join ip in ItemPrices 
    on 
    new { p.PriceId, ItemId = 7 } 
    equals 
    new { ip.PriceId, ip.ItemId } 
    into priceItemPrice 
    from pip in priceItemPrice.DefaultIfEmpty() 
    select new 
    { 
     pricesPriceId = p.PriceId, 
     z = (int?)pip.PriceId, 
     p.Content, 
     p.PriceMinQ 
    }