查询基类型时,为什么EF提供程序会生成所有这些UNION All子句

时间:2010-11-08 18:13:59

标签: linq linq-to-entities

如果我的模型看起来像这样: alt text

我按照以下方式执行Linq to Entities查询:

var c = MyContext.Contact.Count();

我会得到一个与所有门一样大的SQL查询!

SELECT 
[GroupBy1].[A1] AS [C1]
FROM ( SELECT 
    COUNT(1) AS [A1]
    FROM   [dbo].[Contacts] AS [Extent1]
    LEFT OUTER JOIN  (SELECT 
        [UnionAll1].[Id] AS [C1]
        FROM  (SELECT 
            [Extent2].[Id] AS [Id]
            FROM [dbo].[Companies] AS [Extent2]
        UNION ALL
            SELECT 
            [Extent3].[Id] AS [Id]
            FROM [dbo].[Employees] AS [Extent3]) AS [UnionAll1]
    UNION ALL
        SELECT 
        [Extent4].[Id] AS [Id]
        FROM [dbo].[Contractors] AS [Extent4]) AS [UnionAll2] ON [Extent1].[Id] = [UnionAll2].[C1]
    LEFT OUTER JOIN  (SELECT 
        [UnionAll3].[Id] AS [C1]
        FROM  (SELECT 
            [Extent5].[Id] AS [Id]
            FROM [dbo].[Suppliers] AS [Extent5]
        UNION ALL
            SELECT 
            [Extent6].[Id] AS [Id]
            FROM [dbo].[Customers] AS [Extent6]) AS [UnionAll3]
    UNION ALL
        SELECT 
        [Extent7].[Id] AS [Id]
        FROM [dbo].[People] AS [Extent7]) AS [UnionAll4] ON [Extent1].[Id] = [UnionAll4].[C1]
)  AS [GroupBy1]

在我看来,这应该是一个非常简单的查询,它在基本类型表上执行(在这种情况下是联系人)我在这里包含的模型是我正在使用的一个淡化的样本。正如您可以想象的那样,层次结构为6级而不是3级,除了大多数派生类型之外的任何SQL查询都非常昂贵。

有没有办法调整查询或模型定义以减少此查询的不必要的复杂性。

1 个答案:

答案 0 :(得分:1)