Repository navigation
Open
Open
Copy link
Milestone
Description
The following query is not working:
var test = await this.dbcontext.MyEntity
.GroupBy(x => x.Status)
.ToDictionaryAsync(x => x.Key.Name, y => y?.Count() ?? 0);If you are seeing an exception, include the full exceptions details (message and stack trace).
Exception message: EF.Property called with wrong property name
Stack trace: Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)\r\n at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.VisitBinary(BinaryExpression binaryExpression)\r\n at Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerSqlTranslatingExpressionVisitor.VisitBinary(BinaryExpression binaryExpression)\r\n at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.Translate(Expression expression)\r\n at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.WeakEntityExpandingExpressionVisitor.Expand(Expression source, MemberIdentity member)\r\n at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.WeakEntityExpandingExpressionVisitor.VisitMember(MemberExpression memberExpression)\r\n at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.WeakEntityExpandingExpressionVisitor.Expand(SelectExpression selectExpression, Expression lambdaBody)\r\n at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.RemapLambdaBody(ShapedQueryExpression shapedQueryExpression, LambdaExpression lambdaExpression)\r\n at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateGroupBy(ShapedQueryExpression source, LambdaExpression keySelector, LambdaExpression elementSelector, LambdaExpression resultSelector)\r\n at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)\r\n at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)\r\n at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)\r\n at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)\r\n at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)\r\n at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass12_0`1.<ExecuteAsync>b__0()\r\n at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)\r\n at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)\r\n at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query, CancellationToken cancellationToken)\r\n at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken)\r\n at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetAsyncEnumerator(CancellationToken cancellationToken)\r\n at System.Runtime.CompilerServices.ConfiguredCancelableAsyncEnumerable`1.GetAsyncEnumerator()\r\n at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.<ToDictionaryAsync>d__155`3.MoveNext()\r\n at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n at Test.Service.DataService.<GetFilesAsync>d__31.MoveNext() in C:\\Test\\Visual Studio Projects\\Test\\Test.Service\\DataService.cs:line 821
Steps to reproduce
var test = await this.dbcontext.MyEntity
.GroupBy(x => x.Status)
.ToDictionaryAsync(x => x.Key.Name, y => y?.Count() ?? 0);Further technical details
EF Core version: 3.0.0-preview8.19374.2
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: Windows 10
IDE: 16.2.0 Preview 4.0
Reacted by Anduin Xue, Yan , Eduardo Larios, Arad Alvand, Fabien Ménager, mojtaba kaviani and KLuuKer
Activity
divega commentedon Jul 26, 2019
@kccsf do you expect the aggregate function (COUNT) to be evaluated in memory or on the server?
kccsf commentedon Jul 26, 2019
@divega - Thanks for the response. I would expect it to be evaluated server side.
ajcvickers commentedon Jul 26, 2019
@kccsf Do you have the same expectation for
ToDictionary(i.e. non-async)?kccsf commentedon Jul 27, 2019
@ajcvickers - Yes; IMHO it is less confusing if async/non async functions perform in the same manner (server side or client side) unless there is a compelling reason that they shouldn't?
My preference of server side is purely down to not wishing to retrieve a potentially large amount of records when all I need is a count for a high level summary.
divega commentedon Jul 31, 2019
@kccsf It is important for you to know that the lambda expressions passed to either
ToDictionaryorToDictionaryAsyncare never passed to EF Core, and therefore are never translated to the server.This is because
ToDictionaryandToDictionaryAsyncare always evaluated on the client and the lambdas passed to them are of typeFunc<T>rather thanExpression<Func<T>>expressions which could be parsed and translated by EF Core.For
ToDictionarythis is a bit more "by-design" because it is actually a method onSystem.Linq.Enumerablethat uses theIEnumerable<T>aspect of the query to enumerate all the results and then create the dictionary, but we definedToDictionaryAsyncas an operator overIQueryable<T>in EF Core, and we did not consider making its lambda arguments translatable.There is an ongoing discussion on what to do about this in the long term. See #16838 for one possible way to address it.
divega commentedon Jul 31, 2019
In the meantime, the correct way to write this query is:
(Note that I haven't tried this on a real application, so you could still run into other issues).
kccsf commentedon Jul 31, 2019
@divega - Thanks for the explanation and the corrected query. An analyzer such as that mentioned in the thread to which you linked could indeed be helpful.
Unfortunately, the rewritten query still suffers from the original issue - EF.Property called with wrong property name.
Slightly different stack trace:
smitpatel commentedon Jul 31, 2019
Is
Statusa navigation? Then #15249kccsf commentedon Jul 31, 2019
@smitpatel - it is indeed. I'll keep an eye on that issue. Thanks
divega commentedon Jul 31, 2019
@smitpatel wouldn't it be possible to workaround #15249 by explicitly grouping on the key of Status?
smitpatel commentedon Jul 31, 2019
Yes, that works. If you project scalar property out of navigation (or even anonymous type if more than one property it would work.
kccsf commentedon Jul 31, 2019
@divega - Do you mean like so?
If so that does not help as I need the non grouped property x.Key.Name which would then not be available.
smitpatel commentedon Jul 31, 2019
divega commentedon Jul 31, 2019
@kccsf, @smitpatel understood, thanks for the additional details. I am guessing that if the Name of Status is guaranteed somehow to be unique, you can use it directly as the key of the groups, simplifying the query to:
You may need to create additional database indexes for this query to be evaluated more efficiently on the server. I hope this helps.
kccsf commentedon Jul 31, 2019
@divega / @smitpatel - Very kind but I already have a workaround in the form of FromSqlRaw, so unless you wish to have something here for others who hit this issue please don't waste your precious time on it!
@divega - Thanks but name is not unique.
@smitpatel - Thanks but fails in the same manner (EF.Property called with wrong property name):
It is still the GroupBy failing (EF.Property called with wrong property name):
smitpatel commentedon Jul 31, 2019
Missed that part. GroupBy does not expand navigation so you would have to generate manual join.
[-]EF.Property called with wrong property name[/-][+]Introduce an IQueryable ToDictionary method (to align with async) and translate it[/+]Shane32 commentedon Apr 2, 2020
I'd like to see
ToDictionaryadded and the arguments translated. I would never have expected thatIQueryable.ToDictionaryAsyncwould not translate the expression. (I don't typically examine the parameters enough to notice that it accepts a Func rather than an Expression.) It would seem to be extremely simple to convert this to.Select.ToListAsync.ToDictionarywithin the EF library, if that's the ideal path at present, allowing for performance improvements in the future.If, on the other hand,
IQueryable.ToDictionaryAsyncwas not present, I would notice and write.Select.ToListAsync.ToDictionaryin my user code. So I would consider it a poor design decision to addIQueryable.ToDictionaryAsyncwithout it accepting expressions as parameters.Here is a working sample of an enhanced ToDictionaryAsync function:
I also ran a few tests on one of my production Azure databases which has 66,000 records and a bunch of columns:
As you can imagine, 'a' and 'b' took 3.5 to 4.5 seconds each, while 'c' took 60 to 300ms. It might be even faster if the PartNumber field was indexed.
For bonus points, I'd like to see ToHashSet and ToHashSetAsync added as well.
roji commentedon May 22, 2021
See #20076 for possibly introducing an IQueryable ToList/ToArray as well.