Closed ascott18 closed 6 years ago
@ascott18 Can you provide details how to extract the generated expressions in above issue? (Or did you just use the debugger?)
@StefH I got it through the debugger (query.Expression.DebugView). Here's a full project that reproduces the issue:
Here it is a bit cleaner. Also added another query to show the same behavior without using a dynamic expression: QueryBugCleanedUp.zip
Here's an alternative using the Z.Expressions library.
QueryBug-ZExpressionAlternative.zip
string expression = $@"OrderBy(r => r.ParentEntity == null ? """" : r.ParentEntity.Name).ThenBy(r => r.Name);";
var dynamicQuery = context.RootEntities
.Include(r => r.ParentEntity)
.Include(r => r.Children)
.Execute<IQueryable<RootEntity>>(
expression);
There is an issue in both EF Core & Linq.Dynamic (https://github.com/StefH/System.Linq.Dynamic.Core), but arguably Linq.Dynamic is more at fault than EF Core, since it is (in part) designed to work with EF Core, and EF Core works perfectly when constructing the same statement with a compiler-interpreted lambda.
The issue is as follows:
Given a model like the following (See comment below for a full repro project.):
The following will work:
And the following will NOT work:
The exception thrown by the second case:
The expression generated by the correct, working query:
The expression generated by Linq.Dynamic that causes the error inside EF Core:
EF Core is getting confused by the object cast here and going down some code path that eventually ends in an error. This issue ONLY happens when the child collection is included. If the include of the child collection is removed, no error occurs.