2 回答

TA貢獻1780條經驗 獲得超1個贊
這里問題的核心是,AppDbContext正在創建兩個實例來執行一項操作。更改是在一個實例中進行的,并SaveChanges在另一實例上調用。顯然,它沒有反映在底層數據庫中。
我們現在將從下到上逐步檢查您的代碼。
在ATM.ConsoleUICore.Program.Main()方法中,注意以下代碼:
AccountService accountService = new AccountService();
...
...
...
accountService.DepositAmount(bankAccount, 50);
您正在創建 的實例AccountService。在 的構造函數中AccountService,您將創建一個實例,UnitOfWork如下所示:
private readonly UnitOfWork uow;
public AccountService()
{
uow = new UnitOfWork();
}
在 的構造函數中UnitOfWork,您正在創建 的一個實例AppDbContext(派生自DbContext)。
您還擁有BankAccounts財產,它是一個實例,RepositoryBankAccount如下所示:
private readonly AppDbContext db;
public UnitOfWork()
{
db = new AppDbContext();
}
...
...
...
private RepositoryBankAccount _BankAccounts;
public RepositoryBankAccount BankAccounts
{
get
{
if (_BankAccounts == null)
{
_BankAccounts = new RepositoryBankAccount();
}
return _BankAccounts;
}
}
現在問題...
在 的構造函數中RepositoryBankAccount,您再次創建 的實例,AppDbContext如下所示:
public AppDbContext context { get; }
public RepositoryBankAccount()
{
context = new AppDbContext();
}
實際上,您假裝您在一個UnitOfWork實例下的操作正在作為一個數據庫事務執行。但是,當您在存儲庫中創建不同的實例時AppDbContext,情況并非如此。您的工作單元與存儲庫分離。你必須將它們連接起來。它應該是AppDbContext到處相同的實例。
那么,解決辦法是什么呢?
不要在任何存儲庫中創建 的實例AppDbContext。相反,從工作單元注入現有實例。
public AppDbContext context { get; }
public RepositoryBankAccount(AppDbContext appDbContext)//<==Inject the AppDbContext
{
context = appDbContext;//<==Do NOT create new instance here; assign the injected instance.
}
然后,在您的UnitOfWork班級中,更改屬性,BankAccounts如下所示:
private RepositoryBankAccount _BankAccounts;
public RepositoryBankAccount BankAccounts
{
get
{
if (_BankAccounts == null)
{
_BankAccounts = new RepositoryBankAccount(db);//<==Note that `db` means `AppDbContext` is injected
}
return _BankAccounts;
}
}
順便說一句,避免所有這些不必要的包裝紙。
看看這個答案,它解釋了為什么不需要這樣的包裝器。
以防萬一您決定繼續現有的設計,我已經在上面建議了一個解決方案。
此外,我建議您的一個工作單元應該是一個數據庫事務。因此,數據庫事務在您創建工作單元實例時開始,并在您處置它時結束(提交或回滾)。要么所有內容都刷新到數據庫,要么什么都不刷新。在此期間發生的所有事情都應該是一個數據庫事務的一部分。如果出現異常,則一起回滾工作單元。

TA貢獻1816條經驗 獲得超4個贊
對任何數據庫事務嘗試這種格式。創建多個實例
public RepositoryTransaction()
{
context = new AppDbContext();
}
只是意味著您每次創建實例并且它不會保存到數據庫中。
using(AppDbContext db = new AppDbContext())
{
var transaction = new Transaction()
{
BankAccountId = bankAccount.Id,
Amount = amount,
TransactionDateTime = DateTime.Now,
TransactionType = TransactionType.Deposit
};
// save them back to the database
//Add new Employee to database
db.Transactions.InsertOnSubmit(transaction);
//Save changes to Database.
db.SubmitChanges();
}
using(AppDbContext db = new AppDbContext())
{
// get the record
Transaction dbProduct = db.Transactions.Single(p => p.BankAccountId == 1);
// set new values
dbProduct.TransactionDateTime = DateTime.Now;
dbProduct.TransactionType = TransactionType.Deposit;
// save them back to the database
db.SubmitChanges();
}
- 2 回答
- 0 關注
- 150 瀏覽
添加回答
舉報