Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 498
  • Last Modified:

Explanation - MVC


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
                //if the item does not exist in the cart then add one to the quantity
            //Save changes

Can anyone explain this to me?  Especially the "SingleOrDefault" part.
2 Solutions
Julian HansenCommented:
Does this help

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.
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  ; )

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now