public bool Buy(ItemToSale product, out string errorMessage) { errorMessage = null; if (!EnoughMoneyToBuy(product)) { errorMessage = "Недостаточно внесено денег для покупки"; return false; } using (var context = new VendingContext()) { var coinsInserted = context.MoneyCache.Select(x => x.Count * x.Nominal).ToList(); var moneyInCacheCount = coinsInserted.Aggregate((arg1, arg2) => arg1 + arg2); var needReturn = moneyInCacheCount - product.Price; foreach (var coins in context.MoneyCache) { AddToBank(coins.Nominal, coins.Count, context); } foreach (MoneyCache cache in context.MoneyCache) { cache.Count = 0; } ReturnToCache(needReturn, context); var productToBuy = context.ItemsToSale.First(x => x.Id == product.Id); productToBuy.AvailableCount -= 1; context.SaveChanges(); } return true; }
public void AddProduct(ItemToSale item) { using (var context = new VendingContext()) { context.ItemsToSale.Add(item); context.SaveChanges(); } }
private bool EnoughMoneyToBuy(ItemToSale product) { var coins = GetCacheCoins(); return coins.Count != 0 && coins.Select(x => x.Count * x.Nominal).Aggregate((n, m) => n + m) >= product.Price; }