'Is Using EF Core Value Converter Preventing the Contains() LINQ Method from being Translated to SQL?
I have a Movie class. It has a Genres property of type List<string>. I use this exact EF Core Value Conversion to store it in the database as a comma-separated string.
In my method, I have movies, which is of type IQueryable<Movie>. The method receives genres as a List<string>, and I want to filter the movies according to the genres.
When I apply this filter, this query fails to translate to the database.
var genre = "Drama";
movies = movies.Where(m => m.Genres.Contains(genre));
The filter works if I apply .ToListAsync() to movies and pull all the movies to the client-side. But I'm trying to find a way to do this on the database-side.
I've also tried these variations:
movies = movies.Where(m => m.Genres.Any(g => g.Contains(genre)));
movies = movies.Where(m => m.Genres.Any(g => g == genre));
I'm pasting in the error message below:
.Where(m => m.Genres .Contains(__genre_0))' could not be translated. Additional information: Translation of method 'System.Linq.Enumerable.Contains' failed. If this method can be mapped to your custom function, see https://go.microsoft.com/fwlink/?linkid=2132413 for more information. 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.
If you want to reproduce it on your computer:
- Clone this github repository (filter-translation-issue branch)
- Put a breakpoint on
SearchMoviesExtendedQuery.cs, line 53. - Run the project(
APIshould be the startup project), it will create theFreeFlixDatabaseSQL Server database and seed ten movies, then it will open Swagger UI. - In the Swagger UI, run the
/api/catalog/MoviesSearchPOST method with the message body:{"genres":["string"]}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
