In my .NET 6,0 app I'm trying to use (new to .NET 6.0 https://learn.microsoft.com/en-us/dotnet/api/system.linq.queryable.distinctby?view=net-6.0) method DistinctBy, something like this:
return context.Table
.Where(x => x.IsLive)
.DistinctBy(x => x.Field1)
.ToList();
Buld is fine, no errors, but at runtime I get this:
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.NotSupportedException: LINQ to Entities does not recognize the method 'System.Linq.IQueryable`1[MyType] DistinctBy[DbFundHistoPrice,String](System.Linq.IQueryable`1[VanEck.Repositories.Entities.Website.Funds.DbFundHistoPrice], System.Linq.Expressions.Expression`1[System.Func`2[VanEck.Repositories.Entities.Website.Funds.DbFundHistoPrice,System.String]])' method, and this method cannot be translated into a store expression.
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.DefaultTranslator.Translate(ExpressionConverter parent, MethodCallExpression call)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.MethodCallTranslator.TypedTranslate(ExpressionConverter parent, MethodCallExpression linq)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.TranslateExpression(Expression linq)
at System.Data.Entity.Core.Objects.ELinq.ExpressionConverter.Convert()
at System.Data.Entity.Core.Objects.ELinq.ELinqQueryState.GetExecutionPlan(Nullable`1 forMergeOption)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass41_0.<GetResults>b__1()
at System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction[T](Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<>c__DisplayClass41_0.<GetResults>b__0()
at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute[TResult](Func`1 operation)
at System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__31_0()
at System.Data.Entity.Internal.LazyEnumerator`1.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
*my call here*
Other queries without new .NET 6 methods work fine (upgrading from 5 so there are some).
What am I missing here? Somethig in startup or in project settings?
I know that these extensions can be trimmed during build but I see no reason for that here since the method is actually used.
CodePudding user response:
It seems you are using older ORM (EF 6?) which does not support this method.
DistinctBy
is not supported even by EF Core (which I recommend upgrading to) at the moment. See this issue - Translate LINQ DistinctBy. You can try rewriting it with GroupBy(e => e.Field1).Select(g => g.First())
.
See also: