efcore icon indicating copy to clipboard operation
efcore copied to clipboard

Executing .Contains on a static collection

Open Mike5246 opened this issue 3 years ago • 2 comments
trafficstars

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<Request>() .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

Mike5246 avatar Nov 29 '21 08:11 Mike5246

@smitpatel to suggest workarounds.

ajcvickers avatar Dec 02 '21 17:12 ajcvickers

context.Requests
    .Where(x => x.UserName == "test") // use || if there are multiple columns to match
    .Select(x => x.Id)
    .ToList();

smitpatel avatar Dec 02 '21 23:12 smitpatel