When quering over a base type why does the EF provider generate all those UNION All clauses

纵然是瞬间 提交于 2020-01-09 12:03:25

问题


If I have a model that looks like this:

and I do a Linq to Entities query like this:

var c = MyContext.Contact.Count();

I'll get a SQL query that is as big as all out doors!

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]

It seems to me that this should be a very simple query that executes over the base type table (Contact in this case) The model that I've included here is a watered down sample of what I'm working with. As you can imagine with a hierarchy 6 levels deep rather than 3 the SQL queries on anything other than the most derived types are very expensive.

Is there any way to tweek the query, or the model definition to reduce the unnecessary complexity of this query.


回答1:


It's arguably a bug, and will be fixed RSN.



来源:https://stackoverflow.com/questions/4126668/when-quering-over-a-base-type-why-does-the-ef-provider-generate-all-those-union

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!