I’m trying to filter a table using where clause. When I the write the queries separately they work fine:
IQueryable<Movie> movies = db.Movies;
movies = movies.Where(movie =>
movie.MovieToGenres.Any(genreItem => genreItem.Genre_ID == 34)
);
movies = movies.Where(movie =>
movie.MovieToGenres.Any(genreItem => genreItem.Genre_ID == 35)
);
However I have to use it in a foreach loop:
List<int> genre_ids = new List<int>();
genre_ids.Add(34);
genre_ids.Add(35);
IQueryable<Movie> movies = db.Movies;
foreach (var genre_id in genre_ids)
{
movies = movies.Where(movie =>
movie.MovieToGenres.Any(genreItem => genreItem.Genre_ID == genre_id)
);
}
When I do that, on the SQL side the query parameters are @p0 = 35, @p1 = 35 instead of @p0 = 34, @p1 = 35. I don’t know why.
It’s another case of capturing the loop variable. There’s only one
genre_idvariable which is captured by all the lambda expressions. It’s easy to fix by introducing a new variable on each iteration, and capture that instead:In C# 5 this may be unnecessary – the behaviour may well be changing.