asp.net-core - EFCore 中的可查询<T>.Union 行为

标签 asp.net-core entity-framework-core

从而实现相当于TSQL UNION :

SELECT Blogid, Url
FROM Blogs
UNION (SELECT Blogid, Url
        FROM Blogs)
ORDER BY url

我尝试使用 Queryable.Union<T> ( doc ) 和“最终用户”的输出是相同的,但是当使用 SQL Server Profiler 时我可以看到对同一个表的两个查询

例如(SQL Profiler 的输出):

使用 EFCore

SELECT [b1].[BlogId], [b1].[Url]
FROM [Blogs] AS [b1]
go
SELECT [b2].[BlogId], [b2].[Url]
FROM [Blogs] AS [b2]
go

“对”

在 Management Studio 上查询

SELECT Blogid, Url
FROM Blogs
UNION (SELECT Blogid, Url
        FROM Blogs)
ORDER BY url

根据this blog post

EF translates Union to Union ALL with SELECT DISTINCT, so eventually each result is unique.

EF 中查询的核心如下:

DbSet<Blog> set = db.Set<Blog>();
List<Tuple<string,int>> blogs = set.Union(set).OrderBy(blog => blog.Url).ToList();

请注意 Union没有翻译,也没有 GroupBy 。 使用GroupBy没有Union ,使查询被翻译为

SELECT [blog].[Url] , [blog].[BlogId] 
FROM [Blogs] AS [blog]
ORDER BY [Url]

这是预期的行为。 为什么不是 Union翻译正确吗?

最佳答案

链接的文章描述了这种行为,您只是忽略了它。

EF Core supports Union for entity and primitive types locally.

强调位于本地一词上。从 EF Core 2.0 开始,许多 EF Core Linq 运算符(例如 GroupBy 等)尚未转换为 SQL。话虽这么说,任何 group by 操作都将在 EF Core 2.0 或更低版本的内存中执行。

本文中翻译的查询是关于 EF(基于旧的 .NET Framework 的 EntityFramework 6.x)的。另请注意,您问题中的 MSDN 链接适用于旧的 EntityFramework(最高 6.x)。 EF Core 通常位于 learn.microsoft.com 域中。

EF Core 2.1 将改进许多缺失的翻译。看看EF Core 2.1 Roadmap当然还有2.1 Milestone on GitHub以查看详细的改进。

另请参阅this issue其中涵盖了 Union/Except/Intersect/Concat Linq 运算符的服务器端翻译。

其标签为“punted-for-2.1”。因此,如果时间允许,它可能会在 EF Core 2.1 发布之前的时间范围内完成,否则可能会出现在 EF Core 2.1 中,否则它将出现在下一个版本中。

关于asp.net-core - EFCore 中的可查询<T>.Union 行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48988623/

相关文章:

c# - 如何使 Entityframework Core 设置正确的参数数据类型

asp.net-core - Entity Framework ApplicationUser 子实体返回 null

c# - 无法翻译 LINQ 表达式。要么以可翻译的形式重写查询,要么显式切换到客户端评估

c# - 使用 Entity Framework 的 C# 中的通用存储库

asp.net-core - Visual Studio 2015 中支持 ASP.NET Core?

asp.net-core - ASP.NET Core 中使用的 lambda 配置模式的名称是什么?

c# - aspnet core web.config 未加载

postgresql - 如何在模型中自动包含多个导航?

c# - 如何减少 ASP.NET Core 中的 cookie 大小(类似于使用引用模式)?

asp.net-core - 使用 .Net Core API 进行元组序列化