how to pass selectmany combine with groupby to MVC

2019-08-09 02:21发布

问题:

i have the following lambda expression in MVC application.

 var toprating=  _db.Movie.SelectMany(m => m.Rating.Select(r=> new 

            {

           movieID=r.MovieID,
           MovieTitle= m.Title
            })).GroupBy(m=>m.movieID).ToList();

      ViewBag.TopMovie = toprating;
        }

i want to pass this to my view. i try writing the following in my view

 IEnumerable<Movie> TopMovies = ViewBag.TopMovie;

but got this error

Cannot implicitly convert type 'object' to 'System.Collections.Generic.IEnumerable<Movie>'. An explicit conversion exists (are you missing a cast?)

any help will be appriciated.

回答1:

i would recommend that you make a class that depicts your domain entity (Movie) like

public class MyMovie{
 public int movieID { get; set; }
 public string MovieTitle { get; set; }  
}

and modify your linq query as

var toprating=  _db.Movie.SelectMany(m => m.Rating.Select(r=> new MyMovie
            {
              movieID=r.MovieID,
              MovieTitle= m.Title
            })).GroupBy(m=>m.movieID).ToList();

ViewBag.TopMovie = toprating;
IEnumerable<MyMovie> TopMovies = ViewBag.TopMovie; 

i have assumed that the Movie is your Domain entity, use view models to pass on to the views.

you may find this helpful