1

我想将 datareader 数据分配到通用 List ( of T ) 中。

我不想阅读特定的列项目名称。我想让它动态化。

示例代码:

Shared Function FormatUserList(ByVal PoReader As OracleDataReader) As List(Of Users)
    Dim oUserList As New List(Of Users)()
    Dim oUser As Users
    Dim dt As New DataTable
    dt = PoReader.GetSchemaTable()

    Do While PoReader.Read()
        Dim index As Integer = 0
        oUser = New Users()

        oUser.LoginId = Convert.ToString(PoReader("LoginId"))
        oUser.Password = Convert.ToString(PoReader("Password"))
        oUser.FirstName = Convert.ToString(PoReader("FirstName"))
        oUser.LastName = Convert.ToString(PoReader("LastName"))
        oUser.NRIC = Convert.ToString(PoReader("NRIC"))
        oUser.MobileNo = Convert.ToInt64(PoReader("MobileNo"))
        oUser.Address = Convert.ToString(PoReader("Address"))
        oUser.Zip = Convert.ToInt64(PoReader("Zip"))
        oUser.State = Convert.ToInt64(PoReader("state"))
        oUser.UserGroupId = Convert.ToInt64(PoReader("UserGroupId"))
        oUser.CompanyId = Convert.ToInt64(PoReader("CompanyId"))
        oUser.Active = Convert.ToInt64(PoReader("Active"))
        oUserList.Add(oUser)
    Loop

    Return oUserList
End Function

我需要类似下面的东西,但是在将第二行数据循环到SetValue.

“你调用的对象是空的。”

Do While PoReader.Read()

  oUserGroup = New UserGroups()

  Dim type As Type = GetType(UserGroups) 
  Dim obj As Object = Activator.CreateInstance(type)

    For Each row As DataRow In dt.Rows
        sColName = row.Field(Of String)("ColumnName")
        type.GetProperty(sColName).SetValue(obj, PoReader(row.Field(Of String)("ColumnName")), Nothing)
        oUserGroupList.Add(obj)
    Next row
Loop
4

1 回答 1

0

目前还不清楚dt这里的作用是什么;但是,下面的第二个示例显示了一个非常基本的基于反射的循环(使用 C# - 您必须翻译)。

但是,在这样做之前,我真的认为您应该看一下"dapper",它使数据访问(包括参数化)变得如此简单:

string region = "North";
var people = conn.Query<Person>("select * from People where Region=@region",
           new { region }).ToList();

(支持您想要的大多数常见数据场景,包括类型转换 - 以及比基于 IL 的棒动摇更疯狂的优化)

并通过反射以缓慢的方式进行,例如:

static List<T> Read<T>(IDataReader reader)
    where T : class, new()
{
    List<T> results = new List<T>();
    Type type = typeof(T);

    if (reader.Read())
    {
        // at least one row: resolve the properties
        PropertyInfo[] props = new PropertyInfo[reader.FieldCount];
        for (int i = 0; i < props.Length; i++)
        {
            var prop = type.GetProperty(reader.GetName(i),
                BindingFlags.Instance | BindingFlags.Public);
            if(prop != null && prop.CanWrite) props[i] = prop;
        }

        do
        {
            var obj = new T();
            for (int i = 0; i < props.Length; i++)
            {
                var prop = props[i];
                if (prop == null) continue; // not mapped

                object val = reader.IsDBNull(i) ? null : reader[i];
                prop.SetValue(obj, val);
            }
            results.Add(obj);
        } while (reader.Read());
    }
    return results;
}
于 2013-10-11T08:30:29.943 回答