Сначала у меня есть база данных, приложение-страница .NET core 2.1 Entity Framework.Создание банковского приложения - это домашнее задание, но я не знаю, почему эта маленькая часть не работает.Когда я разбиваю код на отдельные методы, моя транзакция не завершается и даже не откатывается правильно.Я получаю сообщение об ошибке: «Эта транзакция SqlTransaction завершена; она больше не может использоваться».Когда я вытаскиваю код из отдельных методов в «TransferCheckingToSaving», он работает правильно.
Я попытался передать переменную транзакции в качестве входных данных для каждого из под-методов, и эти методы не выдают ошибку.Когда он переходит к фиксации внутри «TransferCheckingToSaving», он выдает ошибку.
public bool TransferCheckingToSaving(long checkingAccountNum, long savingAccountNum, decimal amount, decimal transactionFee)
{
bool ret = false;
using (var contextTransaction = _context.Database.BeginTransaction())
{
try
{
bool updateSavingSuccess = UpdateSavingBalanceTR(savingAccountNum, amount, contextTransaction);
if (updateSavingSuccess != true)
throw new Exception("The saving account balance did not update successfully while transferring from checking to saving");
bool updateCheckingSuccess = UpdateCheckingBalanceTR(checkingAccountNum, -1 * amount, contextTransaction);
if (updateCheckingSuccess != true)
throw new Exception("The checking account balance did not update successfully while transferring from checking to saving");
bool addToTransHistSuccess = AddToTransactionHistory(checkingAccountNum, savingAccountNum, amount, 100, 0, contextTransaction);
if (addToTransHistSuccess != true)
throw new Exception("Failed to update the transaction history while transferring from checking to saving");
else
{
_context.SaveChanges();
contextTransaction.Commit();
ret = true;
CacheAbstraction cabs = new CacheAbstraction();
cabs.Remove(CacheNameFacade.TRCACHENAME + ":" + checkingAccountNum);
}
}
catch(Exception ex)
{
contextTransaction.Rollback();
throw ex;
}
}
return ret;
}
private bool UpdateCheckingBalanceTR(long checkingAccountNum, decimal amount, IDbContextTransaction transaction)
{
bool ret = false;
try
{
using (transaction)
{
CheckingAccounts checkingAcct = (from c in _context.CheckingAccounts where c.CheckingAccountNumber == checkingAccountNum select c).FirstOrDefault<CheckingAccounts>();
checkingAcct.Balance += (decimal)amount;
if (checkingAcct.Balance < 0)
throw new Exception("The checking balance of " + (checkingAcct.Balance -= amount).ToString() + " is too low to complete this transaction");
_context.SaveChanges();
ret = true;
return ret;
}
}
catch (Exception)
{
throw;
}
//return ret;
}
private bool UpdateSavingBalanceTR(long savingAccountNum, decimal amount, IDbContextTransaction transaction)
{
bool ret = false;
try
{
using (transaction)
{
SavingAccounts savingAcct = (from s in _context.SavingAccounts where s.SavingAccountNumber == savingAccountNum select s).FirstOrDefault<SavingAccounts>();
savingAcct.Balance += (decimal)amount;
if (savingAcct.Balance < 0)
throw new Exception("The checking balance of " + (savingAcct.Balance -= amount).ToString() + " is too low to complete this transaction");
_context.SaveChanges();
ret = true;
return ret;
}
}
catch (Exception)
{
throw;
}
}
private bool AddToTransactionHistory(long checkingAccountNum, long savingAccountNum, decimal amount, int transTypeId, decimal transFee, IDbContextTransaction transaction)
{
bool ret = false;
try
{
using (transaction)
{
TransactionHistories transHist = new TransactionHistories
{
CheckingAccountNumber = checkingAccountNum,
SavingAccountNumber = savingAccountNum,
Amount = amount,
TransactionFee = transFee,
TransactionTypeId = (long)transTypeId,
};
_context.TransactionHistories.Add(transHist);
CacheAbstraction cabs = new CacheAbstraction();
cabs.Remove(CacheNameFacade.TRCACHENAME + ":" + checkingAccountNum); //the checking account is the same for each unique user
_context.SaveChanges();
ret = true;
return ret;
}
}
catch (Exception)
{
throw;
}
}
Я ожидаю, что транзакция завершится успешно, но выдает ошибку «Эта SqlTransaction завершена; она больше не может использоваться».Кто-нибудь может указать мне правильное направление?