Non-static method requires a target error when counting

839 views Asked by At

My code:

public IQueryable<Model.Movie> SearchMovies(string sgenre,string syear,string stitle)
        {
            using (var db = new Context())
            {
                var genre = db.Genre.FirstOrDefault(x => x.Name == sgenre);

                var movies = db.Movie.Where(x => x.Genre.Any(y => y.ID == genre.ID));


                List<Movie> empty = new List<Movie>();

                if (movies.ToList().Count() > 0)
                {
                    return movies.ToList().AsQueryable();
                }
                else
                {
                    return empty.ToList().AsQueryable();
                }
            }
        }

Error i get when movie not exist with specified genre:

System.Reflection.TargetException: Non-static method requires a target.

Error line:

if (movies.ToList().Count() > 0)

but if movies exists with specified genre script works.

1

There are 1 answers

5
Vojtech B On

This exception means that some of the variables you are using in your LINQ query is null.

For example:

When x.Gendre is null it will result in this exception:

var movies = db.Movie.Where(x => x.Genre.Any(y => y.ID == genre.ID));

Try change it to:

db.Movie.Where(x => x.Gendre != null&&x.Genre.Any(y => y.ID == genre.ID));