im trying to get datas from database dynamically. i've list<T> select<T>()
method... heres my issue i can get datas by using datareader here is code:
public list<T> Select<T>()
{
Type type = typeof(T);
...
...
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
try
{
SqlCommand sqlCommand = new SqlCommand(selectCommand, connection);
connection.Open();
SqlDataReader sqlReader = sqlCommand.ExecuteReader();
while (sqlReader.Read())
开发者_StackOverflow中文版 {
foreach (PropertyInfo property in type.GetProperties())
{
property.SetValue( property.Name,(PropertyInfo)sqlReader[property.Name],null);
}
typeList.Add((T)Convert.ChangeType(type,typeof(T)));
}
sqlReader.Close();
}
catch (Exception ex)
{
string exc = ex.Message;
}
finally
{
connection.Close();
}
}
return typeList;
}
i can get data but i cannot assign it to my type so i cannot add my type into my typelist, can help me
Before being able to assign properties to a type you need to instantiate it:
T instance = Activator.CreateInstance<T>();
foreach (PropertyInfo property in type.GetProperties())
{
property.SetValue(instance, sqlReader[property.Name], null);
}
typeList.Add(instance);
Also wrap your SqlCommand
in a using
block in order to properly dispose it. Another remark is that you don't need to .Close()
your connection in the finally block, this will automatically be done by the Dispose
method as you've already wrapped the connection in a using
block.
It looks like you want to create an object of type T for each database row.
Then you might constraint your generic to classes with empty constructors:
public List<T> Select<T>() where T : new()
then you can create new T's
while (sqlReader.Read())
{
T item = new T();
foreach (PropertyInfo property in type.GetProperties())
{
// Note the first parameter "item"
property.SetValue(item, sqlReader[property.Name], null);
}
typeList.Add(item);
}
What data types are you trying to convert here? You should probably be selecting data based on query's, this looks like your trying to store the whole database in one randomly provided type. You might be trying to store text in a double...
If you simply want to store all the data from the database, use a DataSet or DataTable.
Also what are you doing here?
property.SetValue( property.Name,(PropertyInfo)sqlReader[property.Name],null);
Looks like your trying to change the property names of the type that is requested...
精彩评论