0

I am currently learning ASP.NET MVC and along with LINQ

I have followed a few tutorials and have a good concept of MVC. I have run into a problem though. I am trying to select a specific row from my table and sent it to the view but I am getting an error.

The code for the select is:

                Movie Mov = new Movie();

        Mov =  from movies in _db.Movies
                    where movies.Title == "Ghostbusters"
                     select movies;

And the error is:

    Error   2   Cannot implicitly convert type 'System.Linq.IQueryable<MvcApplication2.Models.Movie>' to 'MvcApplication2.Models.Movie'. An explicit conversion exists (are you missing a cast?)    C:\Users\user\Desktop\MvcApplication2\MvcApplication2\Controllers\HomeController.cs 22  25  MvcApplication2

Thanks

2 Answers 2

3

Your Linq Query is an IQueriable. That means it is not an object (or objects) of Movie but a sql query to select Movie objects. You need to convert it to an object (or objects) and pass it to the view.

So try this;

 Movie Mov = (from movies in _db.Movies
                where movies.Title == "Ghostbusters"
                 select movies).FirstOrDefault();

 return View(Mov);
Sign up to request clarification or add additional context in comments.

1 Comment

You don't need that ToList there as it will bring the entire rows to memory.
0

You are assigning a query, and not a query result, to Mov.

Do like so:

Mov = (from ... select ...).First();

And by the way, since you're going to fill in Mov with a value from the query, you don't need to initialize it with = new Movie().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.