I was following this tutorial http://www.asp.net/mvc/tutorials/mvc-music-store
when I stumbled on this piece of code.
public ActionResult AddToCart(int id)
{
// Retrieve the album from the database
var addedAlbum = storeDB.Albums
.Single(album => album.AlbumId == id);
// Add it to the shopping cart
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.AddToCart(addedAlbum);
// Go back to the main store page for more shopping
return RedirectToAction("Index");
}
I don’t understand two things:
1)
var addedAlbum = storeDB.Albums
.Single(album => album.AlbumId == id);
What is this code doing? I don’t know what the operator => does. Also I guess .Single is some function for the database?
2)
This function is having a call to itself? I don’t see how it adds the album to the cart this way. Wouldn’t this cause a function to go into an infinite loop?
It seems there are a lot of core C# that you aren’t quite familiar with yet.
the
=>operator is the lambda operator, which is a succinct way of writing an inline function.The
Singlefunction is an extension method which in this case is makes a call to the database. This method makes use of a neat feature known as expression trees to convert the strongly typed C# comparison into the corresponding SQL code. How it works is a pretty advanced topic, so for now just consider it “magic”.The
AddToCartmethod of thecartobject is different from theAddToCartcontroller action method the code is currently in. I don’t have a link for that, since that’s fairly basic object-oriented programming.I would assume that
cart.AddToCartwill actually update the database.Also read up on LINQ for a better understanding. This is most likely either Linq To Sql or LINQ to Entities using the Entity Framework.