开发者

Help using the Repository Pattern?

I am using the Entity Framework with POCO's generated using the T4 Templates. I have the generated classes in a separate assembly.

Ok, so a very simple example:

I have a Category entity in the model which has SubCategories (1-Many with SubCategory).

When I use the 开发者_开发问答following code, I get The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

Public Interface ICategoryRepository
    Inherits IRepository(Of Category)

    Function GetCategories() As IQueryable(Of Category)
    Function GetCategoryByID(ByVal ID As Integer) As Category

End Interface

Public Class CategoryRepository
    Implements ICategoryRepository

    Public Function GetCategories() As System.Linq.IQueryable(Of Business.Category) Implements ICategoryRepository.GetCategories
        Using db As New GTGContainer
            Return db.Categories
        End Using
    End Function

    Public Function GetCategoryByID(ByVal ID As Integer) As Business.Category Implements ICategoryRepository.GetCategoryByID
        Using db As New GTGContainer
            Return db.Categories.FirstOrDefault(Function(x) x.ID = ID)
        End Using
    End Function

End Class

Public Class HomeController
    Inherits System.Web.Mvc.Controller

    Private _CategoryRepository As GTG.Data.Repositories.ICategoryRepository

    Public Sub New()
        Me.New(New GTG.Data.Repositories.CategoryRepository)
    End Sub

    Public Sub New(ByVal Repository As GTG.Data.Repositories.ICategoryRepository)
        _CategoryRepository = Repository
    End Sub

    Function Index() As ActionResult
        Dim m As New HomeViewModel
        m.Categories = _CategoryRepository.GetCategories

        Return View(m)
    End Function

End Class

Public Class HomeViewModel
    Public Property Categories As List(Of GTG.Business.Category)

End Class

Any help would be great. Thanks!


This is because your GetCategories() returns an IQueryable, which is NOT actually an in-memory collection. When your View tries to enumerate it, it attempts to hit the database, which it obviously cannot do. The easy remedy is to turn it into an in-memory collection by calling ToList() in GetCategories(). That is, db.Categories.ToList().


Let the context live through the life of repository.

Public Class CategoryRepository
    Implements ICategoryRepository

    Private dbContext As GTGContainer

    Public Sub New()
        dbContext = New GTGContainer
    End Sub 

    Public Function GetCategories() As System.Linq.IQueryable(Of Business.Category) Implements ICategoryRepository.GetCategories
        Return dbContext.Categories
    End Function

    Public Function GetCategoryByID(ByVal ID As Integer) As Business.Category Implements ICategoryRepository.GetCategoryByID
        Return dbContext.Categories.FirstOrDefault(Function(x) x.ID = ID)
    End Function
End Class
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜