how to pass selectmany combine with groupby to MVC

2019-08-09 02:10发布

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条回答
对你真心纯属浪费
2楼-- · 2019-08-09 02:45

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

查看更多
登录 后发表回答