views:

333

answers:

1

I have a generic repository that I communicate with my object context with. My object context has function imports that I want to be able to call through my generic repository. Currently I call them through an "Execute" function, but this is not ideal because I have to pass in my function name and parameters as strings which can cause run-time exceptions. My function imports map to complex types.

Is there a way to do something similar to:

Dim rep As IRepository(Of ComplexType)

Dim type As ComplexType = rep.Find(where:=Function(t) t.FunctionImport(parm, parm)).First()

Here is my generic repository as is:

Public Class EFRepository(Of T As Class)
Implements IRepository(Of T)

Private _context As ObjectContext
Private _objectSet As IObjectSet(Of T)
Private _objectResult As ObjectResult(Of T)

Private ReadOnly Property Context() As ObjectContext
    Get
        If _context Is Nothing Then
            _context = New SupportSiteContainer()
        End If

        Return _context
    End Get
End Property

Private ReadOnly Property ObjectSet() As IObjectSet(Of T)
    Get
        If _objectSet Is Nothing Then
            _objectSet = Me.Context.CreateObjectSet(Of T)()
        End If

        Return _objectSet
    End Get
End Property

Public Function GetQuery() As IQueryable(Of T) Implements IRepository(Of T).GetQuery
    Return ObjectSet
End Function

Public Function GetAll() As IEnumerable(Of T) Implements IRepository(Of T).GetAll
    Return GetQuery().ToList()
End Function

Public Function Find(ByVal where As Func(Of T, Boolean)) As IEnumerable(Of T) Implements IRepository(Of T).Find

    Return Me.ObjectSet.Where(where)
End Function

Public Function [Single](ByVal where As Func(Of T, Boolean)) As T Implements IRepository(Of T).[Single]
    Return Me.ObjectSet.[Single](where)
End Function

Public Function First(ByVal where As Func(Of T, Boolean)) As T Implements IRepository(Of T).First
    Return Me.ObjectSet.First(where)
End Function

Public Sub Delete(ByVal entity As T) Implements IRepository(Of T).Delete
    Me.ObjectSet.DeleteObject(entity)
End Sub

Public Sub Add(ByVal entity As T) Implements IRepository(Of T).Add
    Me.ObjectSet.AddObject(entity)
End Sub

Public Sub Attach(ByVal entity As T) Implements IRepository(Of T).Attach
    Me.ObjectSet.Attach(entity)
End Sub

Public Sub SaveChanges() Implements IRepository(Of T).SaveChanges
    Me.Context.SaveChanges()
End Sub

Public Function Execute(ByVal functionName As String, ByVal ParamArray parameters() As System.Data.Objects.ObjectParameter) As ObjectResult(Of T) Implements IRepository(Of T).Execute

    Return Me.Context.ExecuteFunction(Of T)(functionName, parameters)
End Function

End Class

+2  A: 

It's fine to use a generic repository, but don't over-use them. If you have entity-specific functionality, you can subtype your generic interface and extend it with the type-specific functions you need.

Craig Stuntz