Good Morning, I have created my first generic method pieced together from a bunch of Google Searches. I would like for someone to look this over and let me know if I am breaking any major rules or if there are ways to improve this method.
The method calls a stored procedure in sql and then uses reflection to assign the properties based on the values read from the DataReader schema. The stored procedures are coded so that they return the exact property names expected by the classes. Here is the code:
public static List<T> GetList<T>(string SQLServer, string DBName,
string ProcedureName, Dictionary<string, string> Parameters )
where T : new()
{
List<T> list = new List<T>();
//Setup connection to SQL
SqlConnection SqlConn = new SqlConnection(ConnectionString(SQLServer, DBName));
SqlCommand SqlCmd = new SqlCommand(ProcedureName, SqlConn);
SqlCmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader reader;
//Process Parameters if there are any
foreach (KeyValuePair<string, string> param in Parameters)
{
SqlCmd.Parameters.AddWithValue(param.Key, param.Value);
}
SqlConn.Open();
reader = SqlCmd.ExecuteReader();
//Get The Schema from the Reader
//The stored procedure has code to return
//the exact names expected by the properties of T
DataTable schemaTable = reader.GetSchemaTable();
List<string> fields = new List<string>();
foreach (DataRow r in schemaTable.Rows)
{
fields.Add(r[0].ToString());
}
while (reader.Read())
{
T record = new T();
foreach (string field in fields)
{
//Assign the properties using reflection
record.GetType().GetProperty(field).SetValue(
record, reader[field],
System.Reflection.BindingFlags.Default,
null,null,null);
}
list.Add(record);
}
return list;
}