0

我正在使用纯 ado.net 进行数据访问。我想知道执行以下操作的最佳实践。

我有一个通用产品类....

Class ProductViewModel

 Property ItemID as int
 Property Title as string
 ' etc, all other properties.......

End Class

然后我有订单类

Class OrdersViewModel

 Public OrderNumber as string
 Public ShipToAddress as string
 ' etc all properties

End Class

我有 10 个其他通用类可用作 ViewModel。

我的问题是针对每个通用类,我需要在我的 VIEW 中提取数据....例如 GetProductID() 函数将返回 ProductID,GetOrderID 将返回OrderID我应该在哪个类中执行实际的数据访问操作?

我应该如何构建我的类,以便我可以更轻松地访问视图中的数据。

谢谢

4

2 回答 2

2

我应该在哪个类中执行数据访问

也不是,您通常会在您的视图/数据访问之间添加一个抽象层,并从那里提取与后端相关的任何内容,例如

Class ProductRepository

Function GetById(ByVal Id As Integer) As Product
    ' Pull product from DB 
End Function

End Class

这被称为存储库模式。拥有存储库后,您可以从后端提取数据并在控制器级别填充视图模型,然后再传递到视图,例如

Public Class ProductsController Inherits System.Web.Mvc.Controller

Function Index(ByVal Id As Integer) As ActionResult
    Dim repo As New ProductRepository()
    ' pull product from DB 
    Dim p As Product = repo.GetById(Id)
    ' populate view model
    Dim model As New ProductViewModel()
    model.ItemID = p.ItemID
    model.Title = p.Title
    ...
    ' pass to view
    Return View(model)
End Function

End Class

以这种方式填充视图模型会变得非常乏味,特别是如果您有负载,我倾向于让AutoMapper等工具为我完成。

于 2013-05-11T07:54:37.057 回答
0

我会做以下事情:

  1. 名为 OrderRepository 的类,您可以在其中对数据库进行所有数据访问

  2. 名为 OrderService 的类,您可以在其中执行所有业务规则

  3. Controller 只能调用 OrderService 类,不能调用 OrderRepository 类。

  4. 控制器应该将 ViewModel 返回给视图

希望这可以帮助

于 2013-05-11T07:32:18.310 回答