Michael Bayer Michael Bayer - 2 months ago 17
Vb.net Question

MVVM Logic layer needs reference to Entity Framework

As a newbie I try to create a MVVM application for learning purposes in VB.NET.

I have four layers - each layer is a separate assembly:

  • Data layer class, that is responsible for access to the database. This assembly has Entity Framework installed. Data layer is referenced by Logic layer.

  • Model layer class, that holds the data (entities), for instance the well known Products, Customers, Orders and so on. Model layer is referenced by Logic layer and ViewModels. Not important yet.

  • Logic layer class, that do business works and tells the data layer what to do. Logic layer references Model layer and Data layer.

  • ViewModels/Views layer (not important yet)

Sample of Data layer:

Public Class DataLayer
Inherits DBContext

Public Sub New(connectionString as String)
End Sub

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

'other CRUD methods
End Class

Sample of Logic layer:

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

When running the application, I face an exception, that the Logic layer needs a reference to Entity Framework. Why this? I thought, the Data layer is the layer, that access the database?

Do I really have to install Entity Framework in the Logic layer assembly? Or what is best practice to access the Data layer in the Logic layer without installing Entity Framework?


Your DataLayer class inherits from DbContext which is type of EntityFramework assembly.

I suggest you create interfaces for Data layer methods in Logic layer(without Entity Framework) first and then implement them in Data layer with EntityFramework.

Logic layer

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

Then in Data layer you just implement interface provided by Logic layer.
Which will prevent you from exposing some data access related types.

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