Linq To Sql Multiple Where Search In Foreach Loop
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_id
variable 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:
foreach (var genre_id in genre_ids)
{
int genreCopy = genre_id;
movies = movies.Where(movie => movie.MovieToGenres.Any(
genreItem => genreItem.Genre_ID == genreCopy));
}
In C# 5 this may be unnecessary - the behaviour may well be changing.
Probably you are looking something like this
List<int> genres = new List<int>() { 34, 35, 36 };
movies = movies.Where(movie => movie.MovieToGenres.Any(genreItem => genres.Contains(genreItem.Genre_ID));
it should translates to IN ( 34, 35, 36)
精彩评论