episode (a) Add all properties of the class as SqlCommand parameters
When executing a stored procedure using SqlCommand, if the stored procedure requires parameters, each parameter must be entered, although the AddWithValue method can be used, but the parameters are still a bit cumbersome.
When you need to use all the properties of a class as arguments, you can get all the properties and values of the class through reflection and add them directly to the parameters.
Note, however, that you must ensure that the class's property name and parameter name are the same (case-insensitive), and that the order does not matter.
1 Private voidSetsqlparameters<t>(SqlCommand cmd, T model)2 whereT:class3 {4 foreach(PropertyInfo propinch 5Model. GetType (). GetProperties (BindingFlags.Instance |bindingflags.public))6 {7Cmd. Parameters.addwithvalue ("@"+ Prop. Name, Prop. GetValue (model,NULL));8 }9}
As you can see, this function uses a loop to iterate through all the properties and use the GetValue method to get the corresponding value, then you can add all the attributes to the argument list in a single sentence.
1 PublicBuilding findbuilding (Building Building)2 {3 using(SqlConnection con =NewSqlConnection (appconnectionstring))4 {5SqlCommand cmd =NewSqlCommand ("findbuilding", con);6Cmd.commandtype =CommandType.StoredProcedure;7Setsqlparameters<building>(cmd, building);8 9 con. Open ();TenSqlDataReader reader =cmd. ExecuteReader (); One if(reader. Read ()) A return NewBuilding - ( -(string) reader["Bldgname"], the(int) reader["Roomnum"] - ); - - return NULL; + } -}
"Doodle Code Deceptive series" episode (a) Add all properties of the class as SqlCommand parameters