How can I fix the cannot convert type error?

后端 未结 2 720
攒了一身酷
攒了一身酷 2021-01-16 20:32

I want to create a details page about a movie, but I´m getting this error and I´m kinda stuck. I\'m getting a cant convert type error. I do understand the error, but I dont

相关标签:
2条回答
  • 2021-01-16 21:14

    You should map your DB (MoviesData) model To Bussiness model (MovieViewModel)

       public ActionResult Details(int Id = 1)
        {
            MoviesData movie = db.MoviesData.Find(Id);
            MovieViewModel MovieVM = new MovieViewModel();
            MovieVM.MovieID = movie.MovieID;
            MovieVM.MovieName = movie.MovieName;
            MovieVM.MovieDescription = movie.MovieDescription;
            MovieVM.MovieCategory = movie.MovieCategory;
            MovieVM.MovieYear = movie.MovieYear;
    
            return View(MovieVM);
        }
    
    0 讨论(0)
  • 2021-01-16 21:17

    In your ActionResult Details method db.MoviesData.Find(Id) returns object which type is WebApplication3.Models.MoviesData but your variable type is MovieViewModel. That's why you are getting exception.

    You need to cast manually. So, You can code like this,

    public ActionResult Details(int Id = 1)
    {
        MoviesData movie = db.MoviesData.Find(Id);
        MovieViewModel MovieVM = new MovieViewModel{
            MovieID = movie.MovieID,
            MovieName = movie.MovieName,
            MovieDescription = movie.MovieDescription,
            MovieCategory = movie.MovieCategory,
            MovieYear = movie.MovieYear
        };
    
        return View(MovieVM);
    }
    
    0 讨论(0)
提交回复
热议问题