2016-11-08 3 views
0

初心者として、私はVB.NETで学習目的でMVVMアプリケーションを作成しようとしています。MVVMロジックレイヤーにEntity Frameworkへの参照が必要

私は4層を持っている - それぞれの層は、別のアセンブリです:データベースへのアクセスを担当して

  • データ層クラス、。このアセンブリには、Entity Frameworkがインストールされています。データレイヤーはロジックレイヤーによって参照されます。

  • よく知られている製品、顧客、注文などのデータ(エンティティ)を保持するモデルレイヤークラスです。 Modelレイヤは、LogicレイヤとViewModelによって参照されます。まだ重要ではありません。

  • 論理層クラスは、ビジネスを行い、データレイヤに何をすべきかを指示します。論理層は、モデル層とデータ層を参照します。

  • の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 

アプリケーションを実行する場合、私はロジック層がEntity Frameworkへの参照を必要とするという例外に直面しています。なぜこれ?私は、データ層は、データベースにアクセスする層だと思った?

LogicレイヤアセンブリにEntity Frameworkをインストールする必要はありますか?または、Entity Frameworkをインストールせずにロジックレイヤーのデータレイヤーにアクセスするベストプラクティスは何ですか?

答えて

1

DataLayerクラスは、EntityFrameworkアセンブリの型であるDbContextから継承します。

まず、Logicレイヤー(Entity Frameworkなし)でデータレイヤーメソッドのインターフェイスを作成し、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

ありがとうございますFabio。私のニーズを少しでも満たしたソリューションで解決しました(私のDatalayerは主に一般的なので、申し訳ありませんが、私はあなたの提案を念頭に置いています)。 –

関連する問題