LINQ with Method Syntax中的JOIN和LEFT JOIN等效项

时间:2012-10-04 17:10:05

标签: sql linq entity-framework

我正在将SQL查询转换为LINQ,它创建一个带有1对1映射的左连接,并且它必须位于方法语法中。我一直在脱掉我的头发试图完成这个没有面纱。我可以在Lambda语法中完成。下面是我尝试运行的示例查询。它们不是实际代码。有人会指出我做错了吗?

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();

1 个答案:

答案 0 :(得分: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不需要左外连接,因为无论如何都会过滤掉null状态。

编辑:不,在查看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();