帮助使用存储库模式?

时间:2011-02-23 04:04:24

标签: asp.net-mvc vb.net entity-framework asp.net-mvc-3 repository-pattern

我正在使用实体框架和使用T4模板生成的POCO。我在单独的程序集中生成了类。

好的,这是一个非常简单的例子:

我在模型中有一个Category实体,它有SubCategories(1-Many with SubCategory)。

当我使用以下代码时,我得到已经处理了ObjectContext实例,并且不能再用于需要连接的操作。

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

任何帮助都会很棒。谢谢!

2 个答案:

答案 0 :(得分:1)

这是因为你的GetCategories()返回一个IQueryable,它实际上并不是内存中的集合。当您的View尝试枚举它时,它会尝试命中数据库,这显然是无法做到的。简单的补救方法是通过调用GetCategories()中的ToList()将其转换为内存中的集合。也就是db.Categories.ToList()。

答案 1 :(得分:-1)

让上下文贯穿存储库的生命。

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