Projection with ternary operator breaks subsequent OrderBy/Where clause
We have several queries which conditionally project an entity using ternary operator. After upgrading from EF6 to EFCore 3.1.5, subsequent OrderBy/Where clause on these queries throws an exception.
Here is a simplified/arbitrary example showing the problem:
this.context.TaxPeriods.Select(x => x.Name != "2018" ? new { x.Name } : new { Name = "2018" }).OrderBy(x => x.Name).ToList();
Exception:
The LINQ expression 'DbSet<TaxPeriod>
.Where(t => t.Name != "2018" ? new { Name = t.Name } : new { Name = "2018" }.Name == "2016")' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.<VisitMethodCall>g__CheckTranslated|8_0(ShapedQueryExpression translated, <>c__DisplayClass8_0& )
at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass9_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
The problem becomes more obvious if we use ternary operator to conditionally project a DTO or null:
this.context.TaxPeriods.Select(x => x.Name != null ? new { x.Name } : null).OrderBy(x => x.Name).ToList();
Exception
The LINQ expression 'DbSet<TaxPeriod>
.OrderBy(t => t.Name != null ? new { Name = t.Name } : null.Name)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.<VisitMethodCall>g__CheckTranslated|8_0(ShapedQueryExpression translated, <>c__DisplayClass8_0& )
at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass9_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetEnumerator()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at ESRI.CAMA.ApplicationLib.Services.DepreciationService.GetCommercialBuildingDepreciations(Guid taxPeriodId) in C:\esri.cama\trunk\src\ESRI.CAMA.ApplicationLib\Services\DepreciationService.cs:line 100
at ESRI.CAMA.API.Controllers.DepreciationController.GetCommercialBuildingDepreciations(Guid taxPeriodId, DataSourceRequest request) in C:\esri.cama\trunk\src\ESRI.CAMA.API\Controllers\DepreciationController.cs:line 50
at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.<InvokeActionMethodAsync>d__12.MoveNext()
Notice the expression is trying to order by "null.Name" in this case.
Possibly related to #14321
Further technical details
EF Core version: 3.1.5 Database provider: Microsoft.EntityFrameworkCore.SqlServer Target framework: .NET Framework 4.8 Operating system: Windows 10 IDE: Visual Studio 2019 16.5.4
The fix for this would be for EF Core to lift the OrderBy, which is presumably what EF6 is doing.
@BabellDev As a workaround, move the OrderBy:
this.context.TaxPeriods.OrderBy(x => x.Name).Select(x => x.Name != null ? new { x.Name } : null).ToList()
Thank you for the response @ajcvickers
Apologies, my examples were likely too trivial to capture the true scope of the issue we are experiencing.
Our production code projects to a DTO before further sorting/filtering. We aggregate/mutate data into the DTO for render in a client-side grid. The sorting/filtering is dynamically applied by that 3rd party grid component (kendo-angular), which appends Where/OrderBy to the IQueryable we generate. Unfortunately that means moving the OrderBy is not feasible for our scenario.
As this ticket is from 2020 is there any chance that it will be fixed?