public async Task<Transaction> CreateTransaction(Book book, Transaction transaction) { DateTime timeStamp = DateTime.Now; if (book == null) throw new PiggyBankDataException("Book object is missing"); if (transaction == null) throw new PiggyBankDataException("Transaction object is missing"); transaction.Book = book; AccountManager acc = new AccountManager(_dbContext); transaction.DebitAccount = await acc.FindAccount(transaction.DebitAccount.Id); transaction.CreditAccount = await acc.FindAccount(transaction.CreditAccount.Id); ValidateTransaction(transaction); transaction.TimeStamp = timeStamp; PiggyBankUtility.CheckMandatory(transaction); _dbContext.Transactions.Add(transaction); await _dbContext.SaveChangesAsync(); return transaction; }
public async Task<Transaction> UpdateTransaction(Transaction transaction) { DateTime timeStamp = DateTime.Now; if (transaction == null) throw new PiggyBankDataException("Transaction object is missing"); Transaction transactionToUpdate = await FindTransaction(transaction.Id); if (!transactionToUpdate.IsValid) throw new PiggyBankDataNotFoundException("Transaction [" + transaction.Id + "] cannot be found"); if (transactionToUpdate.IsClosed) throw new PiggyBankDataException("Closed Transaction cannot be created / updated"); if (transaction.TimeStamp != transactionToUpdate.TimeStamp) throw new PiggyBankDataConcurrencyException("Transaction [" + transaction.Id + "] is being updated by other process"); transaction.Book = transactionToUpdate.Book; AccountManager acc = new AccountManager(_dbContext); transaction.DebitAccount = await acc.FindAccount(transaction.DebitAccount.Id); transaction.CreditAccount = await acc.FindAccount(transaction.CreditAccount.Id); ValidateTransaction(transaction); transaction.TimeStamp = timeStamp; PiggyBankUtility.CheckMandatory(transaction); PiggyBankUtility.UpdateModel(transactionToUpdate, transaction); try { await _dbContext.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { throw new PiggyBankDataConcurrencyException("Transaction [" + transaction.Id + "] is being updated by other process"); } return transactionToUpdate; }