我正在使用实体框架开发一个更大的系统。就个人而言,我确实喜欢用于编写 LINQ/ESQL 查询的基于方法的语法。
但我不知道如何正确编写以下连接查询。
假设,我有以下实体类和 DbContext 存储库:
public class A
{
[Key]
public int ID{get;set;}
public virtual ICollection<B> BCollection { get; set; }
}
public class B
{
[Key]
public int ID { get; set; }
public virtual A A { get; set; }
public virtual ICollection<C> CCollection { get; set; }
public virtual ICollection<D> DCollection { get; set; }
}
public class C
{
[Key]
public int ID { get; set; }
public virtual B B { get; set; }
}
public class D
{
[Key]
public int ID { get; set; }
public virtual B B { get; set; }
}
public class Entities : DbContext
{
public DbSet<A> SetA { get; set; }
public DbSet<B> SetB { get; set; }
public DbSet<C> SetC { get; set; }
public DbSet<D> SetD { get; set; }
}
现在我想得到“整个”树:A类的所有项目,以及它们附加的B类项目,其中B类的每个项目都配备了C类和D类的项目。
我可以用这个查询来做到这一点:
var x = db.SetA
.Include(a => a.BCollection.Select(b => b.CCollection))
.Include(a => a.BCollection.Select(b => b.DCollection))
.ToList();
但我认为这可以更容易地完成,对吧?
请注意:我确实想急切加载整个树,因为我不想使用延迟加载。
编辑:
这不是一个关于单个问题的问题,我的问题更多是关于方法。当我编写如上所示的查询时,EF 会生成一个巨大的查询:
SELECT [Project3].[ID] AS [ID],
[Project3].[C9] AS [C1],
[Project3].[C2] AS [C2],
[Project3].[C3] AS [C3],
[Project3].[C4] AS [C4],
[Project3].[C1] AS [C5],
[Project3].[C5] AS [C6],
[Project3].[C6] AS [C7],
[Project3].[C7] AS [C8],
[Project3].[C8] AS [C9]
FROM (SELECT [Extent1].[ID] AS [ID],
[UnionAll1].[C1] AS [C1],
[UnionAll1].[ID] AS [C2],
[UnionAll1].[ID1] AS [C3],
[UnionAll1].[A_ID] AS [C4],
[UnionAll1].[ID2] AS [C5],
[UnionAll1].[B_ID] AS [C6],
[UnionAll1].[C2] AS [C7],
[UnionAll1].[C3] AS [C8],
CASE
WHEN ([UnionAll1].[ID] IS NULL) THEN CAST(NULL AS int)
ELSE 1
END AS [C9]
FROM [dbo].[A] AS [Extent1]
OUTER APPLY (SELECT CASE
WHEN ([Extent3].[ID] IS NULL) THEN CAST(NULL AS int)
ELSE 1
END AS [C1],
[Extent2].[ID] AS [ID],
[Extent2].[ID] AS [ID1],
[Extent2].[A_ID] AS [A_ID],
[Extent3].[ID] AS [ID2],
[Extent3].[B_ID] AS [B_ID],
CAST(NULL AS int) AS [C2],
CAST(NULL AS int) AS [C3]
FROM [dbo].[B] AS [Extent2]
LEFT OUTER JOIN [dbo].[C] AS [Extent3]
ON [Extent2].[ID] = [Extent3].[B_ID]
WHERE [Extent1].[ID] = [Extent2].[A_ID]
UNION ALL
SELECT 2 AS [C1],
[Extent4].[ID] AS [ID],
[Extent4].[ID] AS [ID1],
[Extent4].[A_ID] AS [A_ID],
CAST(NULL AS int) AS [C2],
CAST(NULL AS int) AS [C3],
[Extent5].[ID] AS [ID2],
[Extent5].[B_ID] AS [B_ID]
FROM [dbo].[B] AS [Extent4]
INNER JOIN [dbo].[D] AS [Extent5]
ON [Extent4].[ID] = [Extent5].[B_ID]
WHERE [Extent1].[ID] = [Extent4].[A_ID]) AS [UnionAll1]) AS [Project3]
ORDER BY [Project3].[ID] ASC,
[Project3].[C9] ASC,
[Project3].[C3] ASC,
[Project3].[C1] ASC
但实际上我自己会写的是这样的:
SELECT *
FROM D RIGHT OUTER JOIN
B ON D.B_ID = B.ID LEFT OUTER JOIN
C ON B.ID = C.B_ID RIGHT OUTER JOIN
A ON B.A_ID = A.ID
我希望这有助于澄清我的问题。重点是:如何让实体框架生成更高效的查询?