在LINQ和实体框架(方法)中执行左/右外连接的最佳方法是什么?

时间:2015-12-15 10:29:19

标签: c# entity-framework linq entity-framework-6

我做了很多搜索,并没有找到我想要的东西。我喜欢添加扩展方法,那么你如何使用扩展方法呢?

1 个答案:

答案 0 :(得分:3)

编写一些扩展方法,使其变得简单易用:

public class JoinResult<TL, TR>
{
    public TL Left { get; set; }
    public TR Right { get; set; }
}

public static IQueryable<JoinResult<TL, TR>> LeftJoin<TL, TR, TKey>(this IQueryable<TL> left, IQueryable<TR> right, Expression<Func<TL, TKey>> leftKeySelector, Expression<Func<TR, TKey>> rightKeySelector)
{
    return left
        .GroupJoin(right, leftKeySelector, rightKeySelector, (l, rightGroup) => new { l, rightGroup = rightGroup.DefaultIfEmpty() })
        .SelectMany(z => z.rightGroup.Select(r => new JoinResult<TL, TR> { Left = z.l, Right = r }));
}

public static IQueryable<JoinResult<TL, TR>> RightJoin<TL, TR, TKey>(this IQueryable<TL> left, IQueryable<TR> right, Expression<Func<TL, TKey>> leftKeySelector, Expression<Func<TR, TKey>> rightKeySelector)
{
    return right
        .GroupJoin(left, rightKeySelector, leftKeySelector, (r, leftGroup) => new { leftGroup = leftGroup.DefaultIfEmpty(), r })
        .SelectMany(z => z.leftGroup.Select(l => new JoinResult<TL, TR> { Left = l, Right = z.r }));
}