Application of attribute in. NET Programming (4)

Source: Internet
Author: User
Document directory
  • Feedback

Sqlcommandgenerator class design

The sqlcommandgenerator class is designed to obtain the parameters of the method through reflection, and assemble a command instance using the parameters marked by sqlcommandparameterattribute.

Referenced namespace:

//SqlCommandGenerator.csusing System;using System.Reflection;using System.Data;using System.Data.SqlClient;using Debug = System.Diagnostics.Debug;using StackTrace = System.Diagnostics.StackTrace;  

Class Code:

Namespace dataaccess {public sealed class sqlcommandgenerator {// private constructor. You cannot use a non-parameter constructor to construct an instance private sqlcommandgenerator () {Throw new notsupportedexception ();} // static read-only field, which defines the parameter name used for the return value public static readonly string returnvalueparametername = "return_value"; // static read-only field, public static readonly object [] novalues = new object [] {}; public static sqlcommand generatecommand (sqlconnection connection, Methodinfo method, object [] values) {// if no method name is specified, obtain the method name from the stack frame if (Method = NULL) method = (methodinfo) (new stacktrace (). getframe (1 ). getmethod (); // obtain the sqlcommandmethodattribute passed in by the method. // This attribute is required to generate a command object using this method. Sqlcommandmethodattribute commandattrisert = (sqlcommandmethodattribute) attribute. getcustomattribute (method, typeof (sqlcommandmethodattribute); debug. Assert (commandattribute! = NULL); debug. assert (commandattrisert. commandtype = commandtype. storedprocedure | commandattriure. commandtype = commandtype. text); // create a sqlcommand object and configure it with the specified attribute. Sqlcommand command = new sqlcommand (); command. connection = connection; command. commandtype = commandattribute. commandtype; // obtain the command text. If not specified, use the method name as the stored procedure name if (commandattribute. commandtext. length = 0) {debug. assert (commandattrisert. commandtype = commandtype. storedprocedure); command. commandtext = method. name;} else {command. commandtext = commandattribute. commandtext;} // call Generator Generatecommandparameters (command, method, values); command. parameters. add (returnvalueparametername, sqldbtype. INT ). direction = parameterdirection. returnvalue; return command;} Private Static void generatecommandparameters (sqlcommand command, methodinfo method, object [] values) {// obtain all the parameters and process them one by one through a loop. Parameterinfo [] methodparameters = method. getparameters (); int paramindex = 0; foreach (parameterinfo paraminfo in methodparameters) {// ignore the IF (attribute) parameter marked as [noncommandparameter. isdefined (paraminfo, typeof (noncommandparameterattribute) continue; // obtain the sqlparameter attribute of the parameter. If this parameter is not specified, create a parameter and use its default settings. Sqlparameterattribute paramattribute = (sqlparameterattribute) attribute. getcustomattribute (paraminfo, typeof (sqlparameterattribute); If (paramattribute = NULL) paramattribute = new sqlparameterattribute (); // use attribute settings to configure a parameter object. Use the defined parameter values. If this parameter is not defined, the parameter value of the method/is inferred. Sqlparameter = new sqlparameter (); If (paramattribute. isnamedefined) sqlparameter. parametername = paramattribute. Name; else sqlparameter. parametername = paraminfo. Name; If (! Sqlparameter. parametername. startswith ("@") sqlparameter. parametername = "@" + sqlparameter. parametername; If (paramattribute. istypedefined) sqlparameter. sqldbtype = paramattribute. sqldbtype; If (paramattribute. issizedefined) sqlparameter. size = paramattribute. size; If (paramattribute. isscaledefined) sqlparameter. scale = paramattribute. scale; If (paramattribute. isprecisiondefined) sqlparameter. prec Ision = paramattribute. precision; If (paramattribute. isdiredefindefined) {sqlparameter. direction = paramattribute. direction;} else {If (paraminfo. parametertype. isbyref) {sqlparameter. direction = paraminfo. isout? Parameterdirection. output: parameterdirection. inputOutput;} else {sqlparameter. direction = parameterdirection. input ;}// check whether sufficient parameter object values are provided by debug. assert (paramindex <values. length); // assign the corresponding object value to the parameter. Sqlparameter. value = values [paramindex]; command. parameters. add (sqlparameter); paramindex ++;} // checks whether there are excess parameter object values in debug. assert (paramindex = values. length );}}}

The necessary work has finally been completed. The code in sqlcommandgenerator is annotated, so it is not difficult to understand. The next step is to use the new method to implement the addcustomer method at the beginning of the previous section.

Refactor the new addcustomer code:

[Sqlcommandmethod (commandtype. storedprocedure)] public void addcustomer ([noncommandparameter] sqlconnection connection, [sqlparameter (50)] string customername, [sqlparameter (20)] string country, [sqlparameter (20)] string Province, [sqlparameter (20)] string city, [sqlparameter (60)] string address, [sqlparameter (16)] string telephone, out int customerid) {customerid = 0; // You Need to initialize the output parameter // call the command generator to generate the sqlcommand instance sqlcommand command = sqlcommandgenerator. generatecommand (connection, null, new object [] {customername, country, province, city, address, telephone, customerid}); connection. open (); command. executenonquery (); connection. close (); // The output parameter value customerid = (INT) command must be explicitly returned. parameters ["@ customerid"]. value ;}

In the code, you must note that the out parameter needs to be initialized in advance and the parameter value is returned to it after the command is executed. Benefiting from attribute, we get rid of the boring coding career. We can even use SQL stored procedures to compile the code that generates the entire method. If we do that, it will save you a lot of time, the code shown in the previous section and this section can be compiled into a component separately, so that you can reuse them continuously in your project. Starting from the next section, we will introduce the application of attribute in a deeper level. Please stay tuned. (To be continued)

Http://www.csdn.net/Develop/Read_Article.asp? Id = 19591

Feedback # Re: Application of attribute in. NET Programming (4)

By wqjch hello, I have read a series of articles on "Application of attribute in. NET programming", and I'm quite interested. But there is another problem: I want to do an experiment. How can I call the program in the following aspects. I do not know the type of the 8th parameters. Can you give me an example. Thank you.
[Sqlcommandmethod (commandtype. storedprocedure)]
Public void addcustomer ([noncommandparameter] sqlconnection connection,
[Sqlparameter (50)] string customername,
[Sqlparameter (20)] string country,
[Sqlparameter (20)] string Province,
[Sqlparameter (20)] string city,
[Sqlparameter (60)] string address,
[Sqlparameter (16)] string telephone,
Out int customerid)
{
Customerid = 0; // The output parameter needs to be initialized.
// Call the command generator to generate a sqlcommand instance
Sqlcommand command = sqlcommandgenerator. generatecommand (connection, null, new object []
{Customername, country, province, city, address, telephone, customerid });

Connection. open ();
Command. executenonquery ();
Connection. Close ();

// The value of the output parameter must be specified.
Customerid = (INT) command. Parameters ["@ customerid"]. value;
}

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.