如何使通用数据库记录到对象转换功能?

时间:2016-02-24 17:34:51

标签: vb.net generics

我使用以下函数从数据库中检索记录并将记录转换为强类型对象的集合。

Private Function GetPlantSettingsFiltered(parameters As Dictionary(Of String, Object), queryCondition As String) As PlantSettings

    Dim query As String
    query = " SELECT * FROM Plant_Settings " _
          + queryCondition

    Dim settings As New PlantSettings
    Dim table As DataTable = GetQueryResults(parameters, query, GetConnectionString("WeighScaleDB"))

    If table Is Nothing Then
        Return settings
    End If

    For Each row As DataRow In table.Rows

        settings.Add(New PlantSetting With {
                     .Setting_ID = ConvertByteArrayToString(TryCast(row("Setting_ID"), Byte())),
                     .Plant_ID = ConvertByteArrayToString(TryCast(row("Plant_ID"), Byte())),
                     .Value = row("Setting_Value").ToString(),
                     .Comments = row("Setting_Comments").ToString()
                 })

    Next

    Return settings

End Function

我想创建一个适用于我的任何对象的函数的泛型版本,而不是为每个对象创建这个函数。

例如,如果调用者可以指定类型,那么其他一些细节,该函数将返回该类型的集合。

Private Function GetObjects(Of T)(parameters As Dictionary(Of String, Object), query As String) As WSAEntityCollection(Of T)

    Dim objectCollection As New WSAEntityCollection(Of T)

    Dim table As DataTable = GetQueryResults(parameters, query, GetConnectionString("WeighScaleDB"))

    If table Is Nothing Then
        Return objectCollection
    End If

    For Each row As DataRow In table.Rows

        ' Here is my problem
        objectCollection.Add(New T With {})

    Next

    Return objectCollection

End Function

我目前的新功能问题是我不知道如何动态地将列名与通用对象的参数匹配。关于如何做到这一点的任何想法?

0 个答案:

没有答案