Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
574 views
in Technique[技术] by (71.8m points)

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

If I have a model that looks like this: alt text

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...