public Order BuyAndRevealListing(AppUser user, int listingId, int price) { Order order = null; if (user.Balance < price) { return(order); } Listing targetListing = listingRepository.GetListingByID(listingId); if (targetListing == null) { return(order); } DateTime orderDate = new DateTime(); orderDate = DateTime.Now; List <ProductKey> keys; ProductKey key = listingRepository.GetProductKeys().Where(k => k.ListingID == listingId).FirstOrDefault(); if (key == null && targetListing.ChildListings != null) { keys = new List <ProductKey>(); foreach (Listing childListing in targetListing.ChildListings) { ProductKey temp = listingRepository.GetProductKeys().Where(k => k.ListingID == childListing.ListingID).SingleOrDefault(); if (temp != null) { keys.Add(temp); } else { return(order); } } } else { keys = new List <ProductKey>() { key }; } order = new Order(user, orderDate); userRepository.InsertOrder(order); unitOfWork.Save(); ProductOrderEntry orderEntry = new ProductOrderEntry(order, targetListing); order.AddProductOrderEntry(orderEntry); //if (targetListing.ChildListings == null || targetListing.ChildListings.Count == 0) //{ foreach (ProductKey productKey in keys) { listingRepository.DeleteProductKey(productKey.ProductKeyID); productKey.Listing.Quantity--; //productKey.Listing.UpdateParentQuantities(); listingRepository.UpdateListing(productKey.Listing); ClaimedProductKey claimedKey = new ClaimedProductKey(productKey, user, orderDate, "Purchase - Order #" + order.OrderID); user.AddClaimedProductKey(claimedKey); claimedKey.IsRevealed = true; userRepository.InsertClaimedProductKey(claimedKey); unitOfWork.Save(); orderEntry.AddClaimedProductKey(claimedKey); } userRepository.InsertProductOrderEntry(orderEntry); unitOfWork.Save(); return(order); }