[英]Managing DbContext Lifetime in a Thick WPF Client
我知道這個問題已經提出並討論了很多(例如Here and Here和這篇文章 )。 盡管如此,我仍然對此感到困惑。 我知道DbContext
不應在應用程序生存期內生存,我知道應在每個Form(窗口)或Presenter中使用它們。 問題是我沒有表格或演示者。 我有一個包含許多視圖模型的窗體(窗口),其中一些在應用程序期間有效,並且幾乎所有視圖模型都依賴於DbContext
(LOB應用程序,WPF,MVVM,Sql Server CE)。
我的解決方案是將DbContext
隱藏在一個工廠后面,該工廠注入到需要訪問DbContext
所有視圖模型中,並且這些視圖模型在加載/卸載其對應視圖時創建/處理DbContext
。 我想知道此解決方案是否有問題,或者是否有更好的解決方案可以建議?
我傾向於將我的項目安排如下:
1)表示層:
Contains my Views and ViewModels
2)業務層:
Contains my business logic
3)數據層:
Contains my models
我的Presentation層調用業務層,以填充要在ViewModel / View中使用的數據的本地副本(保存在ViewModel中)。
這可以通過using語句來實現,例如:
Using DBContext As Entities = ConnectToDatabase()
Dim clsApprovalTypes As New Repositories.clsApprovalTypesRepository(DBContext)
dbResults = clsApprovalTypes.GetRecords()
End Using
Return dbResults
在這里,我只是將上下文傳遞到存儲庫中,一旦返回數據,“最終使用”將處理我的上下文。
要使用在ViewModel / View中所做的更改來更新上下文,我使用AddEdit例程,該例程接受一條記錄,並使用與上述類似的方法,根據需要更新/添加到上下文中,例如:
Using DBContext As CriticalPathEntities = ConnectToDatabase()
Dim clsApprovalTypes As New Repositories.clsApprovalTypesRepository(DBContext)
clsApprovalTypes.AddEditRecord(ApprovalTypeToSave)
Try
clsApprovalTypes.SaveData()
Catch ex As Exception
Return ex
End Try
End Using
我的AddEdit例程類似於
SavedRecord = New ApprovalType 'Store the Saved Record for use later
Dim query = From c In DBContext.ApprovalTypes
Where c.ApprovalType_ID = RecordToSave.ApprovalType_ID
Select c
If query.Count > 0 Then
SavedRecord = query.FirstOrDefault
End If
'
' Use Reflection here to copy all matching Properties between the Source Entity
' and the Entity to be Saved...
'
SavedRecord = Classes.clsHelpers.CopyProperties(RecordToSave, SavedRecord)
If query.Count = 0 Then
Try
DBContext.ApprovalTypes.Add(SavedRecord)
Catch ex As EntityException
Return ex
End Try
End If
我在這里寫了一些有關它的內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.