【乱写代码坑人系列】小插曲(一):将类的所有属性添加为SqlCommand的参数

小插曲(一)将类的所有属性添加为SqlCommand的参数

 

  在使用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         }

  转载请注明出处:LzxHahaha-博客园

posted @ 2015-05-19 00:43  LzxHahaha  阅读(651)  评论(6编辑  收藏  举报