Skip to content

Executing .Contains on a static collection #26841

@Mike5246

Description

@Mike5246

I'm currently migrating a project from EF6 to EF Core. We have a set of queries that use a common logic for filtering. These queries contain a collection that we apply filters for, however, in some cases we need to return just a single value. In order to be able to re-use the filters, we did something like this (a simplified example):

context.Requests
    .Select(x => new
    {
        Id = x.Id,
        UserNames = new string[] { x.UserName },
    })
    .Where(x => x.UserNames.Contains("test")) // this check causes the error
    .Select(x => x.Id) // we do not retrieve the collection, it's just used for filtering
    .ToList();

This works fine in EF6, but in EF Core it throws an exception. Removing the .Where condition stops the exception from being thrown. Is there any way to rewrite this query in EF Core?

Exception message:

{InnerException: null Message: The LINQ expression 'DbSet()
.Where(r => new string[]{ r.UserName }
.Contains("test"))' 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'.

EF Core version: 6.0.0
Database provider: Microsoft.EntityFrameworkCore.SqlServer
Target framework: .NET 6.0

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions