public async Task <Result <Purse> > ConvertMoneyAsync(string userid, string fromcurrency, decimal cashvalue, string tocurrency) { tocurrency = tocurrency?.ToUpper(); fromcurrency = fromcurrency?.ToUpper(); var purseResult = await _purseManager.GetPurseAsync(userid); if (purseResult.Status != ResultEnum.Success) { return(purseResult); } if (cashvalue <= 0) { return(new Result <Purse>(ResultEnum.Error, purseResult.Value, "Invalid cashvalue")); } var checkCurrency = await _currencyConverter.CheckCurrency(tocurrency); if (!checkCurrency) { return(new Result <Purse>(ResultEnum.Error, purseResult.Value, "Сonvertible currency not found in DB")); } var fromBill = purseResult.Value.Bills.SingleOrDefault(from => from.CurrencyName == fromcurrency); if (fromBill != null) { if (fromBill.Cash < cashvalue) { return(new Result <Purse>(ResultEnum.Error, purseResult.Value, "Not enough money for convertation")); } var cashToAdd = await _currencyConverter.GetConvertCashAsync(fromcurrency, cashvalue, tocurrency); if (cashToAdd <= 0) { return(new Result <Purse>(ResultEnum.Error, purseResult.Value, "Error convertation")); } fromBill.Cash -= cashvalue; if (purseResult.Value.Bills.Exists(bill => bill.CurrencyName == tocurrency)) { purseResult.Value.Bills.Single(bill => bill.CurrencyName == tocurrency).Cash += cashToAdd; } else { purseResult.Value.Bills.Add( new Bill { CurrencyName = tocurrency, PurseId = userid, Cash = cashToAdd }); } await _dbContext.SaveChangesAsync(); return(new Result <Purse>(ResultEnum.Success, purseResult.Value, string.Empty)); } else { return(new Result <Purse>(ResultEnum.Error, purseResult.Value, "Invalid bill for convertation")); } }