views:

61

answers:

3

hi,

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.

+1  A: 

do var moviedetail = (Movie)_entities.MovieSet.FirstOrDefault(mvid => mvid.Id == id);

Where is used to return a list, add ToList() and you'll have all the items that matches your id, if your sure there is only one, use First, it will return the first item that matches, FirstOrDefault will return the first that matches or your default object (probably null) if there is no match.

moi_meme
Or Single(...) if you know there's going to be one and only one.
Matt Hamilton
hey buddy,appreciate your help, but i have already tried the solution you mentioned above and i got this message (The method 'Single' is not supported by LINQ to Entities. Consider using the method 'First' instead.)and thats the reason i was using the WHERE propertyany clues ???
Shrewd Demon
A: 

I think, you are getting a collection from the lambda expression. And your view is expecting a single movie object. Since there is a mismatch, it is throwing the error. Just use Single() instead of Where() or use First().

var moviedetail = (Movie)_entities.MovieSet.Single(mvid => mvid.Id == id);

mohang
hey buddy,thanks for the answer but the first or single property will return me either the first or the default single object.where as i want the object that matches the id and hence the where clause...any other clues that i can try ??thanks
Shrewd Demon
+1  A: 

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); 
} 
mohang
100% perfect answer!thanks buddy, this is exactly what was happening...and i tried out as you said and now my code is running smoothly...thanks a ton for the answer !!take care
Shrewd Demon