Introduction
Entity Framework doesn't allow to do left outer join in generic way easily. Every time is is needed developers need to remember quite complex snippet like this:
var leftJoin = p.Person
.GroupJoin(p.PersonInfo,
n => n.PersonId,
m => m.PersonId,
(n, ms) => new { n, ms = ms.DefaultIfEmpty() })
.SelectMany(z => z.ms.Select(m => new { n = z.n, m ));
It is quite difficult to remember when it is used rarely.
This snippet allows to do it much easier like this:
var joined = dbContext.TableA.LeftOuterJoin(dbContext.TableB, a => a.Id, b => b.IdA,
(a, b) => new { a, b, hello = "Hello World!" });
Background
Outer join with a LINQ could be implemented in 3 steps:
var q1 = Queryable.GroupJoin(db.TableA, db.TableB, a => a.Id, b => b.IdA,
(a, b) => new { a, groupB = b.DefaultIfEmpty() });
var q2 = Queryable.SelectMany(q1, x => x.groupB, (a, b) => new { a.a, b });
var q3 = Queryable.SelectMany(db.TableA,
a => q2.Where(x => x.a == a).Select(x => x.b),
(a, b) => new {a, b});
For implementing this steps as an extesnsion we need to build expression trees manually (and it is the hardest part which could be made much easy by this extension).
Using the code
All the code is quite huge and can be found in article attachment.
This code could be used easily as shown in introduction part:
var joined = dbContext.TableA.LeftOuterJoin(dbContext.TableB, a => a.Id, b => b.IdA,
(a, b) => new { a, b, hello = "Hello World!" });
And the generated SQL could look like:
SELECT
1 AS [C1],
[Extent1].[Id] AS [Id],
[Extent1].[Text] AS [Text],
[Join1].[Id1] AS [Id1],
[Join1].[IdA] AS [IdA],
[Join1].[Text2] AS [Text2],
N'Hello World!' AS [C2]
FROM [A] AS [Extent1]
INNER JOIN (SELECT [Extent2].[Id] AS [Id2], [Extent2].[Text] AS [Text], [Extent3].[Id] AS [Id1], [Extent3].[IdA] AS [IdA], [Extent3].[Text2] AS [Text2]
FROM [A] AS [Extent2]
LEFT OUTER JOIN [B] AS [Extent3] ON [Extent2].[Id] = [Extent3].[IdA] ) AS [Join1] ON [Extent1].[Id] = [Join1].[Id2]
And it is quite good.
Points of Interest
There were many hard parts in creating such extensions:
- Creating complex trees manually (compiler will not help us here)
- Reflection is needed for such methods like
Where
, Select
, etc - Avoided using of anonymous types and replace them with Tuples
History
Initial post.