简体   繁体   中英

Cannot set property value to target type from sqldatareader type

List<T> returnList = new List<T>();
conn.Open();
SqlCommand sCmd = new SqlCommand(query, conn);
SqlDataReader dataReader = sCmd.ExecuteReader();
T t = new T();
PropertyInfo[] p = o.GetType().GetProperties();
while(dataReader.Read())
{
    for (int i = 0; i < p.Length; i++)
    {
        Console.WriteLine(p[i].GetValue(t)+" "+p[i].PropertyType+" 
        "+dataReader[i].GetType());
        p[i].SetValue(dataReader[i], t);
    }
    returnList.Add(t);
}
return returnList;

I want to set the value of specific property at run time from sqldatareader object. But i am getting an exception of target type mismatch even though both references are of the same type

You have two problems here. The main one is that you make a wrong call to SetValue() .

From MSDN :

public void SetValue(object obj, object value)

So actually you are calling the method with the wrong placed arguments. Do this and it should be fine:

p[i].SetValue(t, dataReader[i]);

The second problem that you will encounter is that at the end your list will contain only the same object, because you create a new object only once ( T t = new T(); . To solve it, you must place this line inside your while loop.

Also, use using for cleaner code and because you should dispose your command at the end... And close your connection.

All in all, this is the final code:

List<T> returnList = new List<T>();
conn.Open();
using (SqlCommand sCmd = new SqlCommand(query, conn))
{
    SqlDataReader dataReader = sCmd.ExecuteReader();
    PropertyInfo[] p = o.GetType().GetProperties();
    while(dataReader.Read())
    {
        T t = new T();
        for (int i = 0; i < p.Length; i++)
        {
            Console.WriteLine(p[i].GetValue(t)+" "+p[i].PropertyType+" "+dataReader[i].GetType());
            p[i].SetValue(t, dataReader[i]);
        }
        returnList.Add(t);
    }
}
conn.Close();
return returnList;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM