I'm trying to create a LINQ Statement for the following MYSQL Query:
SELECT * FROM Movies
WHERE
movies.Actorid = 1
AND
(
(Movies.Duration >= x1 AND Movies.Duration <= x2) OR
(Movies.Duration >= y1 AND Movies.Duration <= y2) OR
(Movies.Duration >= z1 AND Movies.Duration <= z2)
)
whereas the number of variables (x,y,z) is unknown. Actually they are stored in a Dictionary<int, int> and I'm now trying to create this kind of WHERE condition with a loop, but somehow I couldn't achieve it.
My code looks as follows:
//Initialize query
IQueryable<Movie> query = context.Movies;
//Add actor query
query = query.Where(x => x.Actorid = 1);
//Add duration queries
foreach(KeyValuePair<int, int> movieduration in moviedurations){
query.Where(x => x.Duration >= movieduration.Key && x.Duration <= movieduration.Value);
}
//Execute query
List<Movie> result = query.ToList();
Those conditions are getting connected with a AND condition, but I need an OR condition. So I searched for another solution and found a solution with a custom predict function but somehow, I could't make it work. My try looks like the following:
//Initialize query
IQueryable<Movie> query = context.Movies;
//Add actor query
query = query.Where(x => x.Actorid = 1);
//Define variables
Func<Movie, bool> predicate = movie => false;
//Create predict
foreach(KeyValuePair<int, int> movieduration in moviedurations){
var predicateCopy = predicate;
predicate = x => predicateCopy(x) || (x.Duration >= movieduration.Key && x.Duration <= movieduration.Value);
}
//Add predict to where query
query = query.Where(predicate);
//Execute query
List<Movie> result = query.ToList();
I get the error message:
The type "System.Collections.Generic.IEnumerable<Movie>" cannot be converted into "System.Linq.IQueryable<Movie>".