在使用SqlCommand 執行存儲過程時,如果存儲過程需要參數,就必須將每個參數都輸進去,雖然說可以使用AddWithValue 方法,但參數多時仍舊有些麻煩。
在需要將類的所有屬性作為參數時,可以通過反射獲取這個類所有的屬性和值,並直接添加到參數中。
不過需要注意的是,必須保證類的屬性名和參數名相同(不區分大小寫),順序無所謂。
1 private void SetSqlParameters<T>(SqlCommand cmd, T model)
2 where T : class
3 {
4 foreach (PropertyInfo prop in
5 model.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
6 {
7 cmd.Parameters.AddWithValue("@" + prop.Name, prop.GetValue(model, null));
8 }
9 }
可以看出,這個函數中使用了一個循環來遍歷所有屬性,並使用GetValue 方法來獲得相應的值,之後只需用一句話就可以將所有的屬性加入參數列表中。
1 public Building FindBuilding(Building building)
2 {
3 using (SqlConnection con = new SqlConnection(AppConnectionString))
4 {
5 SqlCommand cmd = new SqlCommand("FindBuilding", con);
6 cmd.CommandType = CommandType.StoredProcedure;
7 SetSqlParameters<Building>(cmd, building);
8
9 con.Open();
10 SqlDataReader reader = cmd.ExecuteReader();
11 if (reader.Read())
12 return new Building
13 (
14 (string)reader["BldgName"],
15 (int)reader["RoomNum"]
16 );
17
18 return null;
19 }
20 }