"Doodle Code Deceptive series" episode (a) Add all properties of the class as SqlCommand parameters

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.