2016-11-08 50 views
0

作爲一名新手,我嘗試在VB.NET中爲學習目的創建一個MVVM應用程序。MVVM邏輯層需要參考實體框架

我有四個層 - 每一層是一個單獨的組件:

  • 數據層類,即負責對數據庫的訪問。此程序集已安裝實體框架。數據層由邏輯層引用。

  • 模型圖層類,包含數據(實體),例如衆所周知的產品,客戶,訂單等。模型層由邏輯層和ViewModels引用。不重要。

  • 邏輯層類,它做生意,並告訴數據層該做什麼。邏輯層參考模型層和數據層。

  • 的ViewModels /瀏覽次數層(未重要而又)數據層的

樣品:

Public Class DataLayer 
    Inherits DBContext 

    Public Sub New(connectionString as String) 
     MyBase.New(connectionString) 
    End Sub 

    Public Function QueryDatabase As IEnumerable(Of T) 
     'Query the database 
    End Public 

    'other CRUD methods 
End Class 

邏輯層的樣品:

Imports Model 
Public Class LogicLayer 
    Private _datalayer As DataLayer 

    Public Sub New() 
     Dim connectionString = GetConnectionStringFromXMLFile 
     _datalayer = new DataLayer(connectionString) 
    End Sub 

    Public Function QueryProducts As IEnumerable(Of Products) 
     Return _datalayer.QueryDatabase(Of Products) 
    End Function 

    'other Methods 
End Class 

運行應用程序時,我面臨一個例外,即邏輯層需要對實體框架的引用。爲什麼這個?我認爲,數據層是訪問數據庫的層?

我真的必須在邏輯層組件中安裝實體框架嗎?或者在不安裝實體框架的情況下訪問邏輯層中的數據層的最佳實踐是什麼?

回答

1

您的DataLayer類繼承自DbContext,它是EntityFramework程序集的類型。

我建議你先在邏輯層(沒有實體框架)中爲數據層方法創建接口,然後用EntityFramework在數據層中實現它們。

邏輯層

Public Interface ICustomerDataService 
    Function GetAll() As IEnumerable(Of Models.Customer) 
    Function GetById(id As Integer) As Models.Customer 
End Interface 

// Logic class depend only on interface 
Public Class CustomerLogic 
    Private ReadOnly _dataService As ICustomerDataService 

    Public Sub New(dataService As ICustomerDataService) 
     _dataService = dataService 
    End Sub 

    Public Sub DoSomeLogicWithCustomer(id As Integer) 
     Dim customer = _dataService.GetById(id) 
     ' do something with customer 
    End Sub 
End Class 

然後,在數據層您剛剛執行由邏輯層提供的接口。
這將阻止你暴露一些數據訪問相關的類型。

Public Class CustomerDataService 
    Implements LogicLayer.ICustomerDataService 

    Public Sub New(context As DbContext) 

    End Sub 

    Public Function GetAll() As IEnumerable(Of Models.Customer) 
     Return context.Customers 
    End Function 
End Class 
+0

謝謝法比奧。我用一種解決方案解決了這個問題,該解決方案能夠更好地滿足我的需求(因爲我的Datalayer主要是通用的;遺憾的是沒有提及這一點),但是我始終牢記您的建議。 –