efcore: Union fails if one query has returned no results
Union fails if one query in the union returns no result. An InvalidOperationException is thrown with the message "When performing a set operation, both operands must have the same include operations. Investigation revealed that if one of the queries in the union is empty (returned no results) the union operation fails. In code example below any or the queries (1, 2, or 3) may return no results.
public async Task<DelimitedList> AvailableClubsAsync(string clubMnemonic = null)
{
using var context = new PGSSqlServerContext();
var query1 = context.Clubs.ForGolferAsync().Where(cl => cl.ClubMnemonic == clubMnemonic)
.Select(cl => new { cl.ClubMnemonic, Sequence = 0 });
var query2 = context.Clubs.ForGolferAsync().Where(cl => !cl.Courses.Any())
.Select(cl => new { cl.ClubMnemonic, Sequence = 1 });
var numberOfTees = await context.Tees.ForGolferAsync().CountAsync().ConfigureAwait(false);
var query3 = context.Courses.ForGolferAsync().Where(co => co.ClubMnemonic != clubMnemonic)
.GroupBy(co => new { co.ClubMnemonic, co.CourseName })
.Where(g => (g.Count() < numberOfTees && g.Key.CourseName == null) || (g.Key.CourseName != null))
.Select(g => new { g.Key.ClubMnemonic, Sequence = 1 });
var query = query1.Union(query2).Union(query3)
.OrderBy(q => q.Sequence).ThenBy(q => q.ClubMnemonic)
.Select(q => q.ClubMnemonic);
return new DelimitedList(list: await query.ToListAsync());
}
Further technical details
EF Core version: 3.1.1 Database provider: (e.g. Microsoft.EntityFrameworkCore.SqlServer) Target framework: (e.g. .NET Core 3.1) Operating system: Windows 10 IDE: (e.g. Visual Studio 2019 164…3)
About this issue
- Original URL
- State: closed
- Created 4 years ago
- Comments: 30 (12 by maintainers)
Commits related to this issue
- Query: Snapshot selector shape correctly for better match If all components are NewExpression are default then just make it wholy default so that it can match to GroupBy-Aggregate shape Resolves #19... — committed to dotnet/efcore by smitpatel 4 years ago
- Query: Snapshot selector shape correctly for better match If all components are NewExpression are default then just make it wholy default so that it can match to GroupBy-Aggregate shape Resolves #19... — committed to dotnet/efcore by smitpatel 4 years ago
I tested a very small subset of a large data access layer. In addition to this problem I also encountered a problem with DefaultIfEmpty not accepting a default value. The performance of various queries was significantly worse than EF6.
I will definitely try again when we get a little closer to the 5.0 release date.
On Fri, Apr 24, 2020 at 7:04 AM Shay Rojansky notifications@github.com wrote:
Note that this has already been fixed in 5.0.0-preview1 - you can give that a try as well. It would be great to get confirmation that the bug is gone.
The select is not applied to GroupBy before comparing shapes for set operations causing the shape to mismatch and throw the exception.