在LINQ和实体框架(方法)中执行左/右外部联接的最佳方式是什么
本文关键字:外部 是什么 方式 最佳 执行 实体 LINQ 框架 方法 | 更新日期: 2023-09-27 18:26:53
我对此进行了大量搜索,但并没有真正找到我要找的东西。我喜欢添加扩展方法,那么如何使用扩展方法呢?
编写一些扩展方法,使其变得简单明了:
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 }));
}