Search code examples
linqodatanetflix

Request Genres by MovieId using LINQ to Netflix OData


I am trying to create a LINQ query to return genres by movieid. The LINQ works in LINQPAD4. Can someone help me with the proper syntax? I am getting the following errors:

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Linq.IQueryable'. An explicit conversion exists (are you missing a cast?)

and

Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List'

Code:(note I have wrapped Title in the following line with parenthesis, but are actually brackets in my code.

public List(Genre) GetGenresByMovieId(string movieid)
{
var genres = from t in MovieCatalog.Titles
where t.Id == "BVlLx"
select t.Genres; return genres.ToList();
}


Solution

  • The right query would look like

    public IEnumerable<Genre> GetGenresByMovieId(string movieId)
    {
        return from title in ctx.Titles
               from genre in title.Genres
               where title.Id == "BVlLx"
               select genre;
    }
    

    In the method call syntax, you need to use SelectMany, not Select, since the filter on titles returns a list of titles (which will always contain just one title, but the compiler doesn't know that) and so you want to "concatenate" all genres for each title in the results.

    The return type is actually IQueryable, but if you only plan to enumerate over it, you can use IEnumerable, or call ToList() to force execution right there in the method (the way I wrote it the query would actually execute only once you try to enumerate it).