Why my Entity Framework creates several queries instead of a single UNION query?

独自空忆成欢 提交于 2019-12-10 16:20:24

问题


I use Entity Framework Core 2.0.1. In my EF query I need to combine several simple queries into a single UNION query. So, for a very basic example, I have a couple of similar queries

using (var dbc = new ItemsDbContext("some-connection-string"))
{
    var q1 = dbc.Items.Where(a => a.ItemType == "A");
    var q2 = dbc.Items.Where(a => a.ItemType == "B");

    var myList = q1.Union(q2).ToList();
}

I would like such SQL statement to be executed, as a single query, against my SQL Server database:

SELECT I.*
    FROM [dbo].[Items]
    WHERE I.ItemType = N'A'
UNION
SELECT I.*
    FROM [dbo].[Items]
    WHERE I.ItemType = N'B'

However, as much as I see in SQL Server Profiler, two separate queries are executed:

Query 1:

SELECT I.*
    FROM [dbo].[Items]
    WHERE I.ItemType = N'A'

Query 2:

SELECT I.*
    FROM [dbo].[Items]
    WHERE I.ItemType = N'B'

Result of this two separate queries is later union'ed by Entity Framework. But it is done in the calling code, not on SQL Server's side.

How can I make Entity Framework Core generate UNION instead of several queries?


回答1:


According to this GitHub issue server-side UNION is simply not implemented yet in EF Core 2.0.1. Server-side UNION is planned to be implemented in EF Core v. 2.1, till then EF will perform local Union (in memory).




回答2:


I tried this in Linqpad

     from x in 
     (from x in TableA select new {A = x.Code, B = x.Name})
    .Concat( from y in TableB select new {A = y.Code, B = y.Name})
    select x

and below is generated SQL Query

SELECT [t2].[Code] AS [A], [t2].[Name] AS [B]
FROM (
    SELECT [t0].[Code], [t0].[Name]
    FROM [coa].[TableA] AS [t0]
    UNION ALL
    SELECT [t1].[Code], [t1].[Name]
    FROM [coa].[TableB] AS [t1]
    ) AS [t2]


来源:https://stackoverflow.com/questions/49597645/why-my-entity-framework-creates-several-queries-instead-of-a-single-union-query

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