add MakeTransfer method in AccountStorage

This commit is contained in:
Zakharov_Rostislav 2024-05-26 16:15:35 +04:00
parent 6fffe7f273
commit 57f1249537
2 changed files with 42 additions and 0 deletions

View File

@ -19,6 +19,7 @@ namespace BankContracts.StoragesContracts
AccountViewModel? GetElement(AccountSearchModel model);
AccountViewModel? Insert(AccountBindingModel model);
AccountViewModel? Update(AccountBindingModel model);
bool MakeTransfer(int recipientId, int senderId, int sum);
AccountViewModel? Delete(AccountBindingModel model);
}
}

View File

@ -95,6 +95,47 @@ namespace BankDatabaseImplement.Implements
return account.GetViewModel;
}
public bool MakeTransfer(int recipientId, int senderId, int sum)
{
using var context = new BankDatabase();
using var transaction = context.Database.BeginTransaction();
try
{
Account? sender = context.Accounts.FirstOrDefault(x => x.Id == senderId);
if (sender == null)
throw new InvalidOperationException("Sender account was not found");
if (sender.Money < sum)
throw new InvalidOperationException("Sender account did not have enough money");
Account? recipient = context.Accounts.FirstOrDefault(x => x.Id == recipientId);
if (recipient == null)
throw new InvalidOperationException("Recipient account was not found");
sender.Update(new AccountBindingModel
{
Id = sender.Id,
Number = sender.Number,
ReleaseDate = sender.ReleaseDate,
ManagerId = sender.ManagerId,
Money = sender.Money - sum,
});
recipient.Update(new AccountBindingModel
{
Id = recipient.Id,
Number = recipient.Number,
ReleaseDate = recipient.ReleaseDate,
ManagerId = recipient.ManagerId,
Money = recipient.Money + sum,
});
context.SaveChanges();
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
return true;
}
public AccountViewModel? Delete(AccountBindingModel model)
{
using var context = new BankDatabase();