Link to home
Start Free TrialLog in
Avatar of AXISHK
AXISHK

asked on

MVC with C#

Reviewing the sinppet on a ebook about MVC implementation and attach a code under Product Controller,

public ActionResult Details(int id)

{
using (var db = new ProductsDataContext())
{
var product = db.Products.SingleOrDefault(x => x.ProductID == id);
if (product == null)
return View("NotFound");
return View(product);
}
}

In (x => x.ProductID == id), does x is the parameter where expression after => is the assignment of a function ? Does I need to define x somewhere in the program ? I guess x refer to a Product object.  Tks
Avatar of kaufmed
kaufmed
Flag of United States of America image

Yes, "x" is a variable declaration. The type of "x" is implicit in this example, but you could explicitly declare it:

e.g.

var product = db.Products.SingleOrDefault(Product x => x.ProductID == id);

Open in new window


So no, you do not need to declare "x" anywhere because that's exactly what that line is doing. Read up on lambda expressions.
Avatar of AXISHK
AXISHK

ASKER

Thanks but i still can't get it, how can x know that it represent a product object ? Can you explain more ? Tks
This is called a Lambda Expression and can be identified as such by the use of the Lambda operator, ->, a hyphen and immediately following it with a greater then sign. On the left side of the lambda operator is the input parameter, which in this case is the variable x and represents a single record from the database table Products. On the right side of the lambda operator is an expression which operates on the record. The query runs through every record in the table Products searching for the one who's ProductID field matches the id variable defined elsewhere in the code. The method SingleOrDefault will return a single record or no records but if more then one record is found an exception is thrown.
Avatar of AXISHK

ASKER

Thanks but my question is how does x know that it represent Product object ,rather than Categoary object for example ? Where can it tell ??
When the statement is executed, var product = db.Products.SingleOrDefault(x => x.ProductID == id);, which is a Linq to Entity Framework query the SingleOrDefault method will go through each of the records passed to it and process it in the lambda expression. As each record is processed the next one come along until all the records have been processed. Think of it as a conveyor belt each record is placed on the conveyor belt and processed through all the methods in the query.
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of AXISHK

ASKER

Tks