efcore icon indicating copy to clipboard operation
efcore copied to clipboard

.Any() in query filter produce "could not be translated. Either rewrite the query in a form that can be translated"

Open v-karnaukhov opened this issue 3 years ago • 20 comments

I use pretty simple entity Request (see example below) and custom query filter ByStatuses as extension. When I use .ToArrayAsync() I got an exception "could not be translated. Either rewrite the query in a form that can be translated"

public class Request
{
    public virtual RequestStatus Status { get; set; }
    public int? StatusId { get; set; }
}

public static IQueryable<Request> ByStatuses(this IQueryable<Request> query, IEnumerable<int> ids)
    {
        return query.Where(o => ids.Any(oo => o.StatusId == oo));
    }

var local = await query.ToArrayAsync();

If I change to this

        return query.Where(o => o.StatusId != null && ids.Any(oo => o.StatusId == oo));

and use .UseRelationalNulls() for context options - this doesnt change anything. Are "Any" and "All" operators doesnt supported in EF 7 pretty well? Or they cant be used in complex query chains? Or this is problem with null property in table row?

The LINQ expression 'oo => EntityShaperExpression: 
    X5.TC5.TC.Domain.Entities.Request
    ValueBufferExpression: 
        ProjectionBindingExpression: EmptyProjectionMember
    IsNullable: False
.StatusId == (int?)oo' 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 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.


   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.VisitLambda[T](Expression`1 lambdaExpression)
   at System.Linq.Expressions.Expression`1.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.VisitBinary(BinaryExpression binaryExpression)
   at Microsoft.EntityFrameworkCore.SqlServer.Query.Internal.SqlServerSqlTranslatingExpressionVisitor.VisitBinary(BinaryExpression binaryExpression)
   at System.Linq.Expressions.BinaryExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.RelationalSqlTranslatingExpressionVisitor.TranslateInternal(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateExpression(Expression expression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateWhere(ShapedQueryExpression source, LambdaExpression predicate)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
   at System.Linq.Expressions.MethodCallExpression.Accept(ExpressionVisitor visitor)
   at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
   at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass12_0`1.<ExecuteAsync>b__0()
   at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
   at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetAsyncEnumerator(CancellationToken cancellationToken)
   at System.Runtime.CompilerServices.ConfiguredCancelableAsyncEnumerable`1.GetAsyncEnumerator()
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.<ToListAsync>d__65`1.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.<ToArrayAsync>d__66`1.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at X5.TC5.TC.Domain.DataAccess.Queries.CommonQueries.<ToDataResultAsync>d__29`2.MoveNext() in C:\Work\Sources\nkz_backend_2\tendercommittee-master\X5.TC5.TC.Domain\DataAccess\Queries\CommonQueries.cs:line 276
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at X5.TC5.TC.Domain.DataAccess.Queries.CommonQueries.<ToDataResultAsync>d__26`2.MoveNext() in C:\Work\Sources\nkz_backend_2\tendercommittee-master\X5.TC5.TC.Domain\DataAccess\Queries\CommonQueries.cs:line 222
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at X5.TC5.TC.Core.Services.DataService.<QueryAsync>d__5`2.MoveNext() in C:\Work\Sources\nkz_backend_2\tendercommittee-master\X5.TC5.TC.Core\Services\DataService.cs:line 48
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at X5.TC5.TC.WebApi.Controllers.Base.DataController`4.<ListImplAsync>d__28.MoveNext() in C:\Work\Sources\nkz_backend_2\tendercommittee-master\X5.TC5.TC.WebApi\Controllers\Base\DataControllerBase.cs:line 131
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at X5.TC5.TC.WebApi.Controllers.Base.DataController`4.<ListAsync>d__21.MoveNext() in C:\Work\Sources\nkz_backend_2\tendercommittee-master\X5.TC5.TC.WebApi\Controllers\Base\DataControllerBase.cs:line 79
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableObjectResultExecutor.<Execute>d__0.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at System.Runtime.CompilerServices.ValueTaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<<InvokeActionMethodAsync>g__Awaited|12_0>d.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<<InvokeNextActionFilterAsync>g__Awaited|10_0>d.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<<InvokeInnerFilterAsync>g__Awaited|13_0>d.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<<InvokeNextResourceFilter>g__Awaited|25_0>d.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<<InvokeFilterPipelineAsync>g__Awaited|20_0>d.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<<InvokeAsync>g__Awaited|17_0>d.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<<InvokeAsync>g__Awaited|17_0>d.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.<Invoke>d__5.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.<Invoke>d__4.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.<Invoke>d__6.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at X5.TC5.TC.WebApi.Startup.<>c.<<Configure>b__8_0>d.MoveNext() in C:\Work\Sources\nkz_backend_2\tendercommittee-master\X5.TC5.TC.WebApi\Startup.cs:line 1012
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at X5.TC5.TC.WebApi.ExceptionHandling.ExceptionHandlerMiddleware.<Invoke>d__5.MoveNext() in 

Include provider and version information

EF Core version: Microsoft.EntityFrameworkCore 7.0.5 Database provider: Microsoft.EntityFrameworkCore.SqlServer 7.0.5 Target framework: .NET 6.0.16 Operating system: Win 10 IDE: (e.g. Visual Studio 2022 17.4)

v-karnaukhov avatar Jun 15 '23 09:06 v-karnaukhov

@v-karnaukhov this should work, can you please submit a minimal, runnable console program showing the failure?

roji avatar Jun 15 '23 09:06 roji

@roji We changed code from return query.Where(o => ids.Any(oo => o.StatusId == oo)); to var local = ids.ToHashSet(); return query.Where(o => local.Contains(o.StatusId)); and exception disappears. I was slightly confused when I saw expression "StatusId == (int?)oo" because it doesn't have a sense

EBiryukow avatar Jun 15 '23 10:06 EBiryukow

var local = ids.ToHashSet(); return query.Where(o => local.Contains(o.StatusId));

This means that your Where is evaluated client-side, in .NET, and so your entire table is potentially being pulled from the database - that's not usually what you want.

Can you produce a minimal, runnable repro of the error occuring?

roji avatar Jun 15 '23 10:06 roji

Repo with a minimal console app: https://github.com/v-karnaukhov/efcoresample01. As we found the root of issue is on nullable StatusId property from Request entity. If we change StatusId to not nullable then it works. But the main problem is we can`t change type of property in real app because of tones of legacy (we are porting from EF6). Is there any chance to use this DTO and this table sctructure to server-side query evaluation with Any operator?

v-karnaukhov avatar Jun 15 '23 14:06 v-karnaukhov

Thanks for the repro - confirmed as a bug in 7.0, we don't translate items.Any(i => i == x) where x is a nullable value type and items is an array of non-nullable value types. The workaround is simply to make your array nullable as well (types in your code sample).

Minimal repro
await using var ctx = new BlogContext();
await ctx.Database.EnsureDeletedAsync();
await ctx.Database.EnsureCreatedAsync();

var values = new[] { 1, 2, 3 };
_ = ctx.Blogs.Where(b => values.Any(v => v == b.Value)).ToList();

public class BlogContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        => optionsBuilder
            .UseSqlServer(@"Server=localhost;Database=test;User=SA;Password=Abcd5678;Connect Timeout=60;ConnectRetryCount=0;Encrypt=false")
            .LogTo(Console.WriteLine, LogLevel.Information)
            .EnableSensitiveDataLogging();
}

public class Blog
{
    public int Id { get; set; }
    public string? Name { get; set; }
    public int? Value { get; set; }
}

This already works on latest main (8.0), thanks to the recent work on Contains. However, it produces an inferior translation:

SELECT [b].[Id], [b].[Name], [b].[Value]
FROM [Blogs] AS [b]
WHERE EXISTS (
    SELECT 1
    FROM OPENJSON(@__values_0) WITH ([value] int '$') AS [v]
    WHERE [v].[value] = [b].[Value])

This uses EXISTS instead of IN; it should be:

SELECT [b].[Id], [b].[Name], [b].[Value]
FROM [Blogs] AS [b]
WHERE [b].[Value] IN (
    SELECT [v].[value]
    FROM OPENJSON(@__values_0) WITH ([value] int '$') AS [v]
)

Note that we translate to EXISTS even if both the column and the array have type int?.

roji avatar Jun 16 '23 06:06 roji

IN or EXISTS is only cosmetic for SQL Server, right?

ErikEJ avatar Jun 16 '23 06:06 ErikEJ

@ErikEJ yes, but this affects the SQL for all databases.

roji avatar Jun 16 '23 06:06 roji

Cool, so affects performance for other engines!

ErikEJ avatar Jun 16 '23 06:06 ErikEJ

Thanks for the repro - confirmed as a bug in 7.0, we don't translate items.Any(i => i == x) where x is a nullable value type and items is an array of non-nullable value types. The workaround is simply to make your array nullable as well (types in your code

@roji Is the are any chances that this issue will be fixed in ef core 7.0 scope? We have a tons of such queries and fixing them is not trivial task.

EBiryukow avatar Jun 16 '23 07:06 EBiryukow

@EBiryukow unfortunately that's very unlikely, as the fix won't be trivial but the workaround is...

roji avatar Jun 16 '23 07:06 roji

This is a bit tricky:

  • We have e.g. NonNullableSource.Any(x => x == NullableItem), and we want to rewrite that to `NonNullableSource.Contains(NullableItem).
  • This doesn't "just work" since Contains's generic type parameter is non-nullable, so it doesn't accept a NullableItem.
  • We could slap a Convert node on the source to convert it to nullable, but that would be illegal in .NET (e.g. can't cast int[] to int?[]); we could make it translate to SQL, but if this ever ends up in client evaluation it would bomb.
  • The right solution is to actually make the source nullable, but it could be an arbitrarily complex tree.
    • This would be a visitor that decends the method chain, converting all of them to be nullable.
    • When it reaches a root (e.g. ParameterQueryRootExpression), it would need to recognize it and make it nullable to. This could get a bit tricky (e.g. primitive collection column).
    • @maumar does this all ring a bell, have we had this problem before?
  • FWIW this is a possible shortcoming of normalizing in preprocessing... If we normalized in translation instead (i.e. QueryableMethodTranslatingEV), we wouldn't need to transform the Expression to another Expression, but rather directly to SQL, and wouldn't have this issue. On the other hand, if anyone decides to bypass QueryableMethodTranslatingEV (we know of one such provider), they lose the normalization.

roji avatar Jun 16 '23 07:06 roji

@roji I've dealt with similar problems in the past (maybe in testing?) and in general changing type from non-nullable to nullable, and propagating it all the way down is a huge mess and resulted is a bunch of bugs due to missing cases (from what I remember).

How about we recognize, rewrite and translate something like this?:

_ = ctx.Blogs.Where(b => values.Any(v => b.Value.HasValue && v == b.Value.Value)).ToList();

maumar avatar Jun 17 '23 09:06 maumar

I've dealt with similar problems in the past (maybe in testing?) and in general changing type from non-nullable to nullable, and propagating it all the way down is a huge mess and resulted is a bunch of bugs due to missing cases (from what I remember).

Yeah, my intuition tells me the same thing... It certainly doesn't seem worth it for this particular optimization.

How about we recognize, rewrite and translate something like this?:

I don't think that helps - note that everything does work currently in 8.0 (we don't need to add HasValue); there's only a SQL quality/perf problem (we produce EXISTS instead of IN)... Basically the optimized SQL with IN gets generated in TranslateContains, and any Any node that gets to translation goes into TranslateAny, which produces the inferior EXISTS.

Since it's not possible to simplify Any to Contains in this scenario in preprocessing (because of the null value type problem), we could pattern in match in translation instead, i.e. pattern-match in TranslateAny and call TranslateContains there; this works because unlike in preprocessing, in translation we don't need to produce a LINQ expression tree, just a SQL one.

If we go down this path, I'd move the simplification entirely from preprocessing to translation (to have it in just one place, taking care of all cases). If we did this in RelationalQueryableMethodTranslatingEV, it would have to be duplicated for non-relational prodicts; instead we could put this in QueryableMethodTranslatingEV to make it common. This would be the only non-abstract method in QueryableMethodTranslatingEV, and provider would need to know to call base.TranslateAny to get the optimization.

I think I'll bring this to design :sweat_smile:

roji avatar Jun 17 '23 12:06 roji

How do you solve it for All

yoganr avatar Oct 20 '23 09:10 yoganr

@yoganr we simplify All with negation (x.All(i => i != foo) => !x.Contains(foo) in the same way, so that would likely error in the same way. But regular all (without negation) doesn't get simplified so there's no issue.

roji avatar Oct 20 '23 10:10 roji

I faced with a similar problem:

var excluded = new List<Customer>();

var result = _dbContext.Customers
    .Where(x => excluded.Any(e => e.Prop1 == x.Prop1 && e.Prop2 == x.Prop2))
    .ToList();

borbiuk avatar Mar 28 '24 13:03 borbiuk

@borbiuk that's unlikely to be related to this issue - please open a new issue with a runnable, minimal code sample.

roji avatar Mar 28 '24 13:03 roji

I am getting the same translation error when I try to match multiple columns. I thought C#8 supports list to json to temporary table for it to translate in to join or something? Any workaround for this?

public class Request
{
    public int Id { get; set; }
    public required string StrId { get; set; }
}

public class Item
{
    public int Id { get; set; }
    public required string StrId { get; set; }
    public int OtherCol {get; set;}
}
void Test(IQueryable<Item> items, IEnumerable<Request> req) {
    var entities = items.Where(x => req.Any(y => y.Id == x.Id && y.StrId == x.StrId)).ToList();
//...
}

lampuiho avatar Nov 18 '25 13:11 lampuiho

@lampuiho your problem is unlikely to be related to what this tracks, can you please open a new issue, and post a fully runnable, minimal repro? The above is just a partial snippet and is insufficient.

roji avatar Nov 18 '25 13:11 roji

@roji if you think it's supposed to be working, then it's probably because we are using the adaptor for mysql not on sql server database. Sorry for the trouble.

lampuiho avatar Nov 19 '25 07:11 lampuiho