.NET 6 LINQ DistinctBy 不支持异常

Iva*_*lov 2 c# linq .net-6.0

在我的 .NET 6,0 应用程序中,我尝试使用(.NET 6.0 新功能https://learn.microsoft.com/en-us/dotnet/api/system.linq.queryable.distinctby?view=net- 6.0)方法 DistinctBy,如下所示:

return context.Table
    .Where(x => x.IsLive)
    .DistinctBy(x => x.Field1)
    .ToList();
Run Code Online (Sandbox Code Playgroud)

Bald 很好,没有错误,但在运行时我得到这个:

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*
Run Code Online (Sandbox Code Playgroud)

其他没有新的 .NET 6 方法的查询工作正常(从 5 升级,所以有一些)。

我在这里缺少什么?启动或项目设置中的某些内容?

我知道这些扩展可以在构建过程中进行修剪,但我认为这里没有理由这样做,因为该方法实际上已被使用。

Gur*_*ron 6

看来您正在使用旧的 ORM(EF 6?),它不支持此方法。

DistinctBy目前甚至 EF Core(我建议升级到)也不支持。请参阅此问题 -翻译 LINQ DistinctBy。你可以尝试重写它GroupBy(e => e.Field1).Select(g => g.First())

也可以看看: