Link to home
Start Free TrialLog in
Avatar of Jasmin01
Jasmin01Flag for South Africa

asked on

Explanation - MVC

Hi.

I am following the Microsoft tutorial to create a music store. Link : http://www.asp.net/mvc/tutorials/mvc-music-store.  

I'm at the point where they are creating the shopping cart, and on the shopping cart class they have the following code:

public void AddToCart(Album album)
        {
            //Get the matching cart and album instances
            var cartItem = storeDB.Carts.SingleOrDefault(
                c => c.CartId == ShoppingCartId
                    && c.AlbumId == album.AlbumId);

            if (cartItem == null)
            {
                //Create a new cart item if no cart item exists
                cartItem = new Cart
                {
                    AlbumId = album.AlbumId,
                    CartId = ShoppingCartId,
                    Count = 1,
                    DateCreated = DateTime.Now
                };
                storeDB.Carts.Add(cartItem);
            }
            else
            {
                //if the item does not exist in the cart then add one to the quantity
                cartItem.Count++;
            }
            //Save changes
            storeDB.SaveChanges();
        }

Can anyone explain this to me?  Especially the "SingleOrDefault" part.
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa 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