如何使用相同的代码从DataRow或DataReader读取?

时间:2011-10-05 19:53:56

标签: .net datareader datarow

目前,我正在使用SqlDataReader加载一个简单的数据库“选择”查询。每行代表一个域对象,所以我像这样膨胀每个对象:

Dim loadedItems As New List(Of Item)
Dim dr As SqlDataReader = GetItemsDataReader()
While dr.Read()
  Dim item As Item = GetItemFromData(dr)
  loadedItems.Add(item)
End While

我写的GetItemFromData方法看起来像这样:

Private Function GetItemFromData(dr As SqlDataReader) As Item
  Dim loadedItem As New Item()
  loadedItem.ID = dr("ID")
  loadedItem.Name = dr("Name")
  'etc., etc.'
  Return loadedItem
End Function

在某些情况下,我必须从DataRow而不是SqlDataReader读取数据。但代码将完全相同!当我查看我的GetItemFromData方法时,我想在dr参数中接受更通用的对象类型,这样我就可以将DataReader视为与DataRow相同因为如果我写一个意图使用DataRow的代码,我会在方法中编写完全相同的代码。有没有办法做到这一点?

2 个答案:

答案 0 :(得分:5)

我能想到的最好方法就是包装几个类并实现一个表面 - 如:

Interface IIndexer
    Default ReadOnly Property Item(ByVal index As String)
End Interface

Class DataReaderWrapper
    Implements IIndexer

    Private ReadOnly _reader As IDataReader

    Public Sub New(reader As IDataReader)
        _reader = reader
    End Sub

    Public ReadOnly Property Item(index As String) As Object Implements IIndexer.Item
        Get
            Return _reader(index)
        End Get
    End Property
End Class

Class DataRowWrapper
    Implements IIndexer

    Private ReadOnly _row As DataRow

    Public Sub New(row As DataRow)
        _row = row
    End Sub

    Public ReadOnly Property Item(index As String) As Object Implements IIndexer.Item
        Get
            Return _row(index)
        End Get
    End Property
End Class

然后,在将行或读者传递给方法之前,您必须将其包装起来:

Private Function GetItemFromData(indexer As IIndexer) As Item
    Dim loadedItem As New Item()
    loadedItem.ID = indexer("ID")
    loadedItem.Name = indexer("Name")
    'etc., etc.'
    Return loadedItem
End Function

Dim i As Item = GetItemFromData(New DataRowWrapper(dr))

答案 1 :(得分:-1)

如何使用DataTable代替:

Dim DataTable table AS new DataTable()
table.Load(GetItemsDataReader())
foreach (DataRow row in table.Rows) {
   Dim item As Item = GetItemFromData(row)
   loadedItems.Add(item)
}

将GetItemFromData()方法更改为DataRow而不是DataReader(抱歉VB.NET / C#混合伪代码)。