开发者

Getting error in MVC Proj while writing Lambda Expression

开发者 https://www.devze.com 2022-12-29 00:31 出处:网络
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

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 开发者_Go百科View(moviedetail);
}

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

thank you.


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); 
} 


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.


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);

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号