I am quite new to MVC from webforms and it has been a really, really steep learning curve for me. Here is the function in the tutorial that I am following:
public ActionResult Index(string id)
{
string searchString = id;
var movies = from m in db.Movies
select m;
if (!String.IsNullOrEmpty(searchString))
{
movies = movies.Where(s => s.Title.Contains(searchString));
}
return View(movies);
}
Here is what I think I know that is happening. The method being an Action result(without parameters) re returning a view. The parameters are added to tell the application to look for a "id" string.
I find the lambda statement a little easier to understand. The if
is checking to see if the searchString
is null if not it returns the movie that matches the description in searchString
.
In the method however, searchString
is given the value of id
in the parameter. Here is where I start getting lost, right after searchString
is defined, a LINQ statement is placed inside the variable movies
. In that statement, what is the purpose of m
? Why is it not defined or is it? The same with the s
in the lambda.
var movies = db.Movies.Select(m => m)
, which is (logically, at least) a no-op (but it depends on the LINQ provider, I'd guess). Basically, this whole things says: "Select all movies, unless there's a search string - in which case, only keep movies that contain that search string."var
.db.Movies
is most likely aDbSet<>
which wouldn't allow for the where to be appended.=>
symbol is not the>=
(greater-or-equal) operator. It's the symbol that denotes a lambda in C#. If you don't know what lambdas are and how they work (at least in C#) and how LINQ works with them, try learning LINQ out of ASP.NET MVC first (because the framework is hard enough to learn even without having to worry about LINQ).var movies = db.Movies as IQueryable<Movie>
, or evenIQueryable<Movie> movies = db.Movies
, instead of writing a whole LINQ expression (and whatever anonymous code it generates) just to assign to a super type.