【发布时间】:2010-11-05 18:25:06
【问题描述】:
早上好,我从一堆 Google 搜索中创建了我的第一个通用方法。我希望有人检查一下,如果我违反了任何主要规则,或者是否有办法改进这种方法,请告诉我。
该方法调用 sql 中的存储过程,然后根据从 DataReader 架构中读取的值使用反射来分配属性。对存储过程进行了编码,以便它们返回类所期望的确切属性名称。代码如下:
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;
}
【问题讨论】:
-
你考虑过 Linq To SQL 吗? weblogs.asp.net/scottgu/archive/2007/05/19/…
-
数据库操作是有代价的。添加反射,它会明显变慢。更糟糕的是,您在循环内执行此操作。您应该将反射部分移到循环之外,并且最好依赖表达式树而不是反射。请参阅此答案stackoverflow.com/a/19845980/661933,例如
标签: c# generics methods class-design