从而实现相当于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
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/