【发布时间】:2019-08-19 10:57:51
【问题描述】:
我有这个银行 ATM 模型应用程序,它实现了一些领域驱动设计架构和工作单元模式。
此应用有 3 个基本功能:
- 查看余额
- 存款
- 退出
这些是项目层:
ATM.Model(领域模型实体层)
namespace ATM.Model
{
public class BankAccount
{
public int Id { get; set; }
public string AccountName { get; set; }
public decimal Balance { get; set; }
public decimal CheckBalance()
{
return Balance;
}
public void Deposit(int amount)
{
// Domain logic
Balance += amount;
}
public void Withdraw(int amount)
{
// Domain logic
//if(amount > Balance)
//{
// throw new Exception("Withdraw amount exceed account balance.");
//}
Balance -= amount;
}
}
}
namespace ATM.Model
{
public class Transaction
{
public int Id { get; set; }
public int BankAccountId { get; set; }
public DateTime TransactionDateTime { get; set; }
public TransactionType TransactionType { get; set; }
public decimal Amount { get; set; }
}
public enum TransactionType
{
Deposit, Withdraw
}
}
ATM.Persistence(持久层)
namespace ATM.Persistence.Context
{
public class AppDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"[connstring]");
}
public DbSet<BankAccount> BankAccounts { get; set; }
public DbSet<Transaction> Transactions { get; set; }
}
}
namespace ATM.Persistence.Repository
{
public class RepositoryBankAccount
{
public AppDbContext context { get; }
public RepositoryBankAccount()
{
context = new AppDbContext();
}
public BankAccount FindById(int bankAccountId)
{
return context.BankAccounts.Find(bankAccountId);
}
public void AddBankAccount(BankAccount account)
{
context.BankAccounts.Add(account);
}
public void UpdateBankAccount(BankAccount account)
{
context.Entry(account).State = EntityState.Modified;
}
}
}
namespace ATM.Persistence.Repository
{
public class RepositoryTransaction
{
private readonly AppDbContext context;
public RepositoryTransaction()
{
context = new AppDbContext();
}
public void AddTransaction(Transaction transaction)
{
context.Transactions.Add(transaction);
}
}
}
namespace ATM.Persistence.UnitOfWork
{
public class UnitOfWork : IUnitOfWork
{
private readonly AppDbContext db;
public UnitOfWork()
{
db = new AppDbContext();
}
private RepositoryBankAccount _BankAccounts;
public RepositoryBankAccount BankAccounts
{
get
{
if (_BankAccounts == null)
{
_BankAccounts = new RepositoryBankAccount();
}
return _BankAccounts;
}
}
private RepositoryTransaction _Transactions;
public RepositoryTransaction Transactions
{
get
{
if (_Transactions == null)
{
_Transactions = new RepositoryTransaction();
}
return _Transactions;
}
}
public void Dispose()
{
db.Dispose();
}
public int Commit()
{
return db.SaveChanges();
}
public void Rollback()
{
db
.ChangeTracker
.Entries()
.ToList()
.ForEach(x => x.Reload());
}
}
}
ATM.ApplicationService(应用层)
namespace ATM.ApplicationService
{
public class AccountService
{
private readonly UnitOfWork uow;
public AccountService()
{
uow = new UnitOfWork();
}
public void DepositAmount(BankAccount bankAccount, int amount)
{
bankAccount.Deposit(amount);
uow.BankAccounts.UpdateBankAccount(bankAccount);
var transaction = new Transaction()
{
BankAccountId = bankAccount.Id,
Amount = amount,
TransactionDateTime = DateTime.Now,
TransactionType = TransactionType.Deposit
};
uow.Transactions.AddTransaction(transaction);
try
{
uow.Commit();
}
catch
{
uow.Rollback();
}
finally
{
uow.Dispose();
}
}
public void WithdrawAmount(BankAccount bankAccount, int amount)
{
bankAccount.Withdraw(amount);
uow.BankAccounts.UpdateBankAccount(bankAccount);
//repoBankAccount.UpdateBankAccount(bankAccount);
var transaction = new Transaction()
{
BankAccountId = bankAccount.Id,
Amount = amount,
TransactionDateTime = DateTime.Now,
TransactionType = TransactionType.Withdraw
};
uow.Transactions.AddTransaction(transaction);
try
{
uow.Commit();
}
catch
{
uow.Rollback();
}
finally
{
uow.Dispose();
}
}
public decimal CheckBalanceAmount(int bankAccountId)
{
BankAccount bankAccount = uow.BankAccounts.FindById(bankAccountId);
return bankAccount.CheckBalance();
}
}
}
ATM.ConsoleUICore
namespace ATM.ConsoleUICore
{
class Program
{
static void Main()
{
AccountService accountService = new AccountService();
RepositoryBankAccount repoBankAccount = new RepositoryBankAccount();
var bankAccount = repoBankAccount.FindById(2);
Console.WriteLine("1. Check balance");
Console.WriteLine("2. Deposit");
Console.WriteLine("3. Withdraw");
Console.WriteLine("Enter option: ");
string opt = Console.ReadLine();
switch (opt)
{
case "1":
Console.WriteLine($"Your balance is ${bankAccount.CheckBalance()}");
break;
case "2":
// User to input amount.
// Data validation to make sure amount is greater than zero.
// Pass the input amount to Application layer.
accountService.DepositAmount(bankAccount, 50);
// After getting the operation status from Application service layer.
// Print operation status here: Either success or fail
Console.WriteLine("Deposit successfully");
break;
case "3":
break;
default:
break;
}
}
}
}
我可以成功检查余额。对于选项 2,我可以执行“存款”选项而不会出现任何错误。但是在数据库中,我的余额余额没有被更新。事务也不会添加到数据库中。
如果我在UpdateBankAccount 方法中放回context.SaveChanges();,它就可以工作。它返回 1。但是,我使用 UoW 执行SaveChanges()。 SaveChanges() 确实在 UoW Commit 方法中执行,但数据库没有反映其更改。 UoW Commit 方法 SaveChanges 返回 0。
完整的代码可以在Github repository找到。
【问题讨论】:
-
您不应该在存储库中创建新的上下文。顺便说一句,主流观点是完全放弃这个多余的 UoW/存储库层。上下文已经是 UoW,DbSet 已经是存储库。
-
如果一个事务失败而另一个事务成功怎么办?这就是我使用 uow 的原因
-
你似乎没有抓住重点。
DbContext== Uow 和DbSet<T>==Repository<T>。一旦您决定使用(冗余)模式,请确保通过在 Uow 和 Repositories 中使用相同的DbContextinstance 来正确实现它们(通过构造函数注入)。目前修改在一个上下文中被跟踪,SaveChages在不同的上下文中被调用,因此没有效果。恕我直言,浪费赏金。
标签: c# entity-framework entity-framework-core repository-pattern unit-of-work