此LINQ查询表达式发出左连接并起作用:
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子句。在“from pip”下不接受where子句,并且在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 vey,我的错误,where子句确实有效 - 出于某种原因,VS2008没有表现出来并让我感到悲伤,我的肚子也在咆哮。我在LinqPad中测试过,where子句很好。所以这个小小的补充确实起作用了:
...
from pip in priceItemPrice.DefaultIfEmpty()
*** where pip.ItemId == null ***
select new
...
答案 0 :(得分: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
}