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.
Jasmin01Asked:
Who is Participating?
 
Julian HansenCommented:
Does this help
http://www.dotnetperls.com/singleordefault

In this context what it is saying is that you want a cart item matching the criteria to be returned.

There should only be one (otherwise you have multiple carts matching the same criteria which is no good). If more than one is found it will throw an exception to tell you something is wrong.

If only one is found that item is returned.

If none is found then the default value for the type is returned.
0
 
käµfm³d 👽Commented:
If none is found then the default value for the type is returned.
...which is always null in the case of classes  ; )
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.