Как обрабатывать объектный контекст с помощью Entity Framework и шаблона репозитория? - PullRequest
1 голос
/ 19 октября 2011

Я использую Entity Framework 4.0 (VS 2010, VB.NET) в своем приложении и пытаюсь сделать это правильно. Мой код выглядит так:

Public Interface ICustomerRepository
  Function GetAll(ByVal preferance As String) As IEnumerable(Of Customer)
End Interface

Реализация интерфейса:

Public Class CustomerRepository

    Implements ICustomerRepository

    Protected objectSet As IObjectSet(Of Customer)

    Public Sub New(ByVal context As ObjectContext)
        Me.objectSet = context.CreateObjectSet(Of Customer)()
    End Sub

    Public Function GetAll(ByVal preferance As String) As
          System.Collections.Generic.IEnumerable(Of Customer) Implements    
          ICustomerRepository.GetAll

          Return Me.objectSet.Where(Function(p) p.preferance = preferance).ToArray
     End Function
End Class

Public Interface IUnitOfWork
   ReadOnly Property Customers() As ICustomerRepository
   Sub Commit()
End Interface

Public Class UnitOfWork
    Implements IUnitOfWork

    Private ReadOnly context As ObjectContext
    Private m_customers As ICustomerRepository


    Public Sub New(ByVal context As ObjectContext)
       If context Is Nothing Then
         Throw New ArgumentNullException("context wasn't supplied")
       End If
       Me.context = context
     End Sub

  Public ReadOnly Property Customers() As ICustomerRepository Implements   
      IUnitOfWork.Customers

    Get
        If Me.m_customers Is Nothing Then
            Me.m_customers = New CustomerRepository(Me.context)
        End If
        Return Me.m_customer
    End Get
   End Property


   Public Sub Commit() Implements IUnitOfWork.Commit
     Me.context.SaveChanges()
   End Sub
End Class

Когда я хочу использовать это на бизнес-уровне:

Using context As New MyDatabseEntities()
Dim uow As New UnitOfWork(context)

For Each customer In uow.Customer.GetAll()
    Console.WriteLine(customer.Name)
Next
End Using

У меня есть несколько репозиториев, Клиент только один (для примера).

Чего я не понимаю…. Когда я пишу, используя контекст Как новый MyDatabseEntities (), не является ли это зависимостью от уровня DAL?

Какое решение лучше?

Должны ли мои репозитории принадлежать DAL или BLL?

И можно ли использовать Защищенный объектный набор как IObjectSet (Of Customer) в моем классе CustomerRepository, или я не должен использовать Of Customer?

Заранее спасибо!

...