返回强类型存储过程结果
目前,如果我们想要从数据库中获取记录列表,我们的 DAL 将返回一个 DataTable 到我们的业务层,然后业务层将相同的 DataTable 返回到我们的调用接口(在本例中是一个 asp.vb 页面)。
但是我不认为我们应该从 BLL 返回 DataTable,我一直认为基于存储过程中的字段返回强类型集合会更好 例如,
public Class MyCustomType
public customerId as int32
public name as string
end Class
public function GetCustomers() as Generic.ICollection(Of MyCustomType)
//call to DAL here
end function
实现此目的的最佳方法是迭代我们的 DataTable,并为每个 DataRow 创建一个新的 MyCustomType 对象并将其添加到集合中,然后返回集合吗?
谢谢。
Currently, if we want to get a list of records from the database, our DAL returns a DataTable to our business layer, which then returns the same DataTable to our calling interface (in this case an asp.vb page).
However I don't believe we should be returning a DataTable from the BLL, I always thought it would be better to return a strongly typed collection based on the fields in the stored procedure
e.g.
public Class MyCustomType
public customerId as int32
public name as string
end Class
public function GetCustomers() as Generic.ICollection(Of MyCustomType)
//call to DAL here
end function
Would the best way to achieve this be iterating over our DataTable, and for each DataRow, create a new MyCustomType object and add it to the collection, then return the collection?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我工作的地方就是这样做的。在我们的例子中,我们得到一个 DataReader 并手动填充类实例的字段。我们还从
List
派生出一个新的列表类型来配合它。确保您对 DBNull.Value 进行了正确的检查并进行了正确的转换等等。That's how we do it where I work. In our case we get a
DataReader
and manually populate the fields of class instance. We also derive a new list type fromList<MyClass>
to go with it. Make sure you do proper checking forDBNull.Value
and proper conversion and all that.看来你的设计试图分离职责,但半途而废。将像 DataTable 这样模糊的东西返回到表示层就是将其隐式地耦合到数据源的特定模式知识。最有可能的是,数据表包含演示文稿甚至不需要的信息。处理 BLL 中的细节并向 PL 返回强类型的有目的对象与您已经尝试设计的模型更加一致。
It seems your design is attempting to separate responsibilities but stops half way. Returning something as nebulous as a DataTable to your presentation layer is implicitly coupling it to specific schema knowledge of the data source. Most likely, the DataTable contains information the presentation doesn't even need. Handling the specifics in your BLL and returning a strongly typed purposeful object to your PL is more consistent with the model it already seems you are attempting to design to.
下面是一个实用程序的链接,该实用程序可以帮助将 DataTable 映射到 MyCustomType 对象:
http://www.eggheadcafe.com/articles/20040221.asp" Eggheadcafe.com/articles/20040221.asp
它有点旧,但可能会有所帮助。也许还有其他一些工具,例如 AutoMapper。
Here's a link to a utility that can help map the DataTable to the MyCustomType object:
http://www.eggheadcafe.com/articles/20040221.asp
It's a bit old, but may be helpful. Perhaps there are some other tools out there as well such as AutoMapper.