Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting error in MVC Proj while writing Lambda Expression

i am creating a sample movie (MVC) application. I was getting fine with Viewing and Creating a new record, but when i wrote the code to get the details of a particular record i met with the following error:

Unable to cast objec`t of type 'System.Data.Objects.ObjectQuery`1[MovieApp.Models.Movie]' to type 'MovieApp.Model`s.Movie'.

here is the code i wrote for getting the details

public ActionResult Details(int id)
{
    var moviedetail = (Movie)_entities.MovieSet.Where(mvid => mvid.Id == id);
return View(moviedetail);
}

can any body tell me whats going wrong and where ??

thank you.

like image 928
Shrewdroid Avatar asked Jun 16 '26 15:06

Shrewdroid


1 Answers

The problem in your code is the Where function returns you IEnumerable and you are typecasting it to Movie. Therefore it is failing. Check for syntax of Where extension function to see for yourself. So if you are sure that you will only be returned one Movie object, I suggest you use First() like this.

public ActionResult Details(int id) 
{ 
    var moviedetail = _entities.MovieSet.Where(mvid => mvid.Id == id).First(); 
    return View(moviedetail); 
} 
like image 78
dotcoder Avatar answered Jun 18 '26 06:06

dotcoder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!