public async Task<Cart> GetCart(string userId, CancellationToken cancellationToken = default(CancellationToken)) { Serilog.Log.Logger.Debug($"{nameof(GetCart)} for user id '{userId}'"); using (var unitOfWork = this.unitOfWorkFunc()) { var cart = await unitOfWork.Value.Repository<Cart>() .Get(c => c.CartId == userId) .SingleOrDefaultAsync(cancellationToken); if (cart == null) { // cart doesn't exist, create it cart = new Cart { CartId = userId }; unitOfWork.Value.Repository<Cart>().Add(cart); await unitOfWork.Value.SaveChangesAsync(cancellationToken); } else { // HACK: .Include(c => c.CartItems.Select(ci => ci.Album)) EF7 doesn't support lazy loading yet and nested includes // using a loop cart.CartItems = await unitOfWork.Value.Repository<CartItem>() .Get(x => x.CartId == cart.CartId, x => x.Album) .ToListAsync(cancellationToken); foreach (var cartItem in cart.CartItems) { cartItem.Album = await unitOfWork.Value.Repository<Album>() .Get(a => a.AlbumId == cartItem.AlbumId) .SingleOrDefaultAsync(cancellationToken); } } return cart; } }
public async Task AddToCart(string cartId, Album album, CancellationToken cancellationToken = default(CancellationToken)) { Serilog.Log.Logger.Debug($"{nameof(this.AddToCart)} album '{album.Title}' for cart with id '{cartId}'"); using (var unitOfWork = this.unitOfWorkFunc()) { var cartRepository = unitOfWork.Value.Repository<Cart>(); var cartItemsRepository = unitOfWork.Value.Repository<CartItem>(); // check if cart exists and create one if it doesn't var existingCart = await cartRepository.Get().SingleOrDefaultAsync(c => c.CartId == cartId, cancellationToken); if (existingCart == null) { existingCart = new Cart {CartId = cartId, CartItems = new List<CartItem>()}; cartRepository.Add(existingCart); } // Get the matching cart and album instances var cartItem = await cartItemsRepository.Get().SingleOrDefaultAsync( c => c.CartId == cartId && c.AlbumId == album.AlbumId, cancellationToken); if (cartItem == null) { // Create a new cart item if no cart item exists cartItem = new CartItem { AlbumId = album.AlbumId, CartId = cartId, Count = 1, DateCreated = DateTime.Now }; cartItemsRepository.Add(cartItem); existingCart.CartItems.Add(cartItem); } else { // If the item does exist in the cart, then add one to the quantity cartItem.Count++; } await unitOfWork.Value.SaveChangesAsync(cancellationToken); } }