Attribute在.NET编程中的应用整理(四)

来源:互联网 发布:淘宝网怎样复制链接 编辑:程序博客网 时间:2024/05/22 14:21

SqlCommandGenerator类的设计

SqlCommandGEnerator类的设计思路就是通过反射得到方法的参数,使用被SqlCommandParameterAttribute标记的参数来装配一个Command实例。

引用的命名空间:

view plaincopy to clipboardprint?
  1. //SqlCommandGenerator.cs   
  2.   
  3.   
  4.   
  5. using System;   
  6.   
  7. using System.Reflection;   
  8.   
  9. using System.Data;   
  10.   
  11. using System.Data.SqlClient;   
  12.   
  13. using Debug = System.Diagnostics.Debug;   
  14.   
  15. using StackTrace = System.Diagnostics.StackTrace;     
  16.   
  17.   
  18.   
  19. 类代码:    
  20.   
  21. namespace DataAccess   
  22.   
  23. {   
  24.   
  25.    public sealed class SqlCommandGenerator   
  26.   
  27.    {   
  28.   
  29.       //私有构造器,不允许使用无参数的构造器构造一个实例   
  30.   
  31.       private SqlCommandGenerator()   
  32.   
  33.       {   
  34.   
  35.          throw new NotSupportedException();   
  36.   
  37.       }   
  38.   
  39.   
  40.   
  41.       //静态只读字段,定义用于返回值的参数名称   
  42.   
  43.       public static readonly string ReturnValueParameterName = "RETURN_VALUE";   
  44.   
  45.       //静态只读字段,用于不带参数的存储过程   
  46.   
  47.       public static readonly object[] NoValues = new object[] {};   
  48.   
  49.       
  50.   
  51.          
  52.   
  53.       public static SqlCommand GenerateCommand(SqlConnection connection,   
  54.   
  55.                                   MethodInfo method, object[] values)   
  56.   
  57.       {   
  58.   
  59.          //如果没有指定方法名称,从堆栈帧得到方法名称   
  60.   
  61.          if (method == null)   
  62.   
  63.              method = (MethodInfo) (new StackTrace().GetFrame(1).GetMethod());   
  64.   
  65.   
  66.   
  67.          // 获取方法传进来的SqlCommandMethodAttribute   
  68.   
  69.          // 为了使用该方法来生成一个Command对象,要求有这个Attribute。   
  70.   
  71.          SqlCommandMethodAttribute commandAttribute =    
  72.   
  73.             (SqlCommandMethodAttribute) Attribute.GetCustomAttribute(method, typeof(SqlCommandMethodAttribute));   
  74.   
  75.   
  76.   
  77.          Debug.Assert(commandAttribute != null);   
  78.   
  79.          Debug.Assert(commandAttribute.CommandType == CommandType.StoredProcedure ||   
  80.   
  81.        commandAttribute.CommandType == CommandType.Text);   
  82.   
  83.   
  84.   
  85.          // 创建一个SqlCommand对象,同时通过指定的attribute对它进行配置。   
  86.   
  87.          SqlCommand command = new SqlCommand();   
  88.   
  89.          command.Connection = connection;   
  90.   
  91.          command.CommandType = commandAttribute.CommandType;   
  92.   
  93.          
  94.   
  95.          // 获取command的文本,如果没有指定,那么使用方法的名称作为存储过程名称    
  96.   
  97.          if (commandAttribute.CommandText.Length == 0)   
  98.   
  99.          {   
  100.   
  101.             Debug.Assert(commandAttribute.CommandType == CommandType.StoredProcedure);   
  102.   
  103.             command.CommandText = method.Name;   
  104.   
  105.          }   
  106.   
  107.          else  
  108.   
  109.          {   
  110.   
  111.             command.CommandText = commandAttribute.CommandText;   
  112.   
  113.          }   
  114.   
  115.   
  116.   
  117.          // 调用GeneratorCommandParameters方法,生成command参数,同时添加一个返回值参数   
  118.   
  119.          GenerateCommandParameters(command, method, values);   
  120.   
  121.          command.Parameters.Add(ReturnValueParameterName, SqlDbType.Int).Direction    
  122.   
  123.                               =ParameterDirection.ReturnValue;   
  124.   
  125.   
  126.   
  127.          return command;   
  128.   
  129.       }   
  130.   
  131.   
  132.   
  133.       private static void GenerateCommandParameters(   
  134.   
  135.                            SqlCommand command, MethodInfo method, object[] values)   
  136.   
  137.       {   
  138.   
  139.   
  140.   
  141.          // 得到所有的参数,通过循环一一进行处理。   
  142.   
  143.             
  144.   
  145.          ParameterInfo[] methodParameters = method.GetParameters();   
  146.   
  147.          int paramIndex = 0;   
  148.   
  149.   
  150.   
  151.          foreach (ParameterInfo paramInfo in methodParameters)   
  152.   
  153.          {   
  154.   
  155.             // 忽略掉参数被标记为[NonCommandParameter ]的参数   
  156.   
  157.             
  158.   
  159.             if (Attribute.IsDefined(paramInfo, typeof(NonCommandParameterAttribute)))   
  160.   
  161.                continue;   
  162.   
  163.                
  164.   
  165.             // 获取参数的SqlParameter attribute,如果没有指定,那么就创建一个并使用它的缺省设置。   
  166.   
  167.             SqlParameterAttribute paramAttribute = (SqlParameterAttribute) Attribute.GetCustomAttribute(   
  168.   
  169.      paramInfo, typeof(SqlParameterAttribute));   
  170.   
  171.       
  172.   
  173.       if (paramAttribute == null)   
  174.   
  175.          paramAttribute = new SqlParameterAttribute();   
  176.   
  177.          
  178.   
  179.       //使用attribute的设置来配置一个参数对象。使用那些已经定义的参数值。如果没有定义,那么就从方法    
  180.   
  181.       // 的参数来推断它的参数值。   
  182.   
  183.       SqlParameter sqlParameter = new SqlParameter();   
  184.   
  185.       if (paramAttribute.IsNameDefined)   
  186.   
  187.          sqlParameter.ParameterName = paramAttribute.Name;   
  188.   
  189.       else  
  190.   
  191.          sqlParameter.ParameterName = paramInfo.Name;   
  192.   
  193.   
  194.   
  195.             if (!sqlParameter.ParameterName.StartsWith("@"))   
  196.   
  197.                sqlParameter.ParameterName = "@" + sqlParameter.ParameterName;   
  198.   
  199.             
  200.   
  201.             if (paramAttribute.IsTypeDefined)   
  202.   
  203.                sqlParameter.SqlDbType = paramAttribute.SqlDbType;   
  204.   
  205.                
  206.   
  207.             if (paramAttribute.IsSizeDefined)   
  208.   
  209.                sqlParameter.Size = paramAttribute.Size;   
  210.   
  211.   
  212.   
  213.             if (paramAttribute.IsScaleDefined)   
  214.   
  215.                sqlParameter.Scale = paramAttribute.Scale;   
  216.   
  217.                
  218.   
  219.             if (paramAttribute.IsPrecisionDefined)   
  220.   
  221.                sqlParameter.Precision = paramAttribute.Precision;   
  222.   
  223.                
  224.   
  225.             if (paramAttribute.IsDirectionDefined)   
  226.   
  227.             {   
  228.   
  229.                sqlParameter.Direction = paramAttribute.Direction;   
  230.   
  231.             }   
  232.   
  233.             else  
  234.   
  235.             {   
  236.   
  237.                if (paramInfo.ParameterType.IsByRef)   
  238.   
  239.                {   
  240.   
  241.                   sqlParameter.Direction = paramInfo.IsOut ?    
  242.   
  243.                               ParameterDirection.Output :    
  244.   
  245.                               ParameterDirection.InputOutput;   
  246.   
  247.                }   
  248.   
  249.                else  
  250.   
  251.                {   
  252.   
  253.                   sqlParameter.Direction = ParameterDirection.Input;   
  254.   
  255.                }   
  256.   
  257.             }   
  258.   
  259.             
  260.   
  261.             // 检测是否提供的足够的参数对象值   
  262.   
  263.      Debug.Assert(paramIndex < values.Length);   
  264.   
  265.               
  266.   
  267.            //把相应的对象值赋于参数。   
  268.   
  269.            sqlParameter.Value = values[paramIndex];   
  270.   
  271.            command.Parameters.Add(sqlParameter);   
  272.   
  273.                      
  274.   
  275.                      
  276.   
  277.            paramIndex++;   
  278.   
  279.          }   
  280.   
  281.          
  282.   
  283.          //检测是否有多余的参数对象值   
  284.   
  285.          Debug.Assert(paramIndex == values.Length);   
  286.   
  287.       }   
  288.   
  289.    }   
  290.   
  291. }  

必要的工作终于完成了。SqlCommandGenerator中的代码都加上了注释,所以并不难读懂。下面我们进入最后的一步,那就是使用新的方法来实现上一节我们一开始显示个那个AddCustomer的方法。

重构新的AddCustomer代码:

view plaincopy to clipboardprint?
  1. SqlCommandMethod(CommandType.StoredProcedure) ]   
  2.   
  3. public void AddCustomer( [NonCommandParameter] SqlConnection connection,    
  4.   
  5.                    [SqlParameter(50)] string customerName,    
  6.   
  7.                    [SqlParameter(20)] string country,    
  8.   
  9.                    [SqlParameter(20)] string province,    
  10.   
  11.                    [SqlParameter(20)] string city,    
  12.   
  13.                    [SqlParameter(60)] string address,    
  14.   
  15.                    [SqlParameter(16)] string telephone,   
  16.   
  17.                    out int customerId )   
  18.   
  19. {   
  20.   
  21.    customerId=0; //需要初始化输出参数   
  22.   
  23.   //调用Command生成器生成SqlCommand实例   
  24.   
  25.    SqlCommand command = SqlCommandGenerator.GenerateCommand( connection, nullnew object[]   
  26.   
  27. {customerName,country,province,city,address,telephone,customerId } );   
  28.   
  29.                             
  30.   
  31.    connection.Open();   
  32.   
  33.    command.ExecuteNonQuery();   
  34.   
  35.    connection.Close();   
  36.   
  37.   
  38.   
  39.    //必须明确返回输出参数的值   
  40.   
  41.    customerId=(int)command.Parameters["@CustomerId"].Value;   
  42.   
  43. }  

代码中必须注意的就是out参数,需要事先进行初始化,并在Command执行操作以后,把参数值传回给它。受益于Attribute,使我们摆脱了那种编写大量枯燥代码编程生涯。 我们甚至还可以使用Sql存储过程来编写生成整个方法的代码,如果那样做的话,可就大大节省了你的时间了,上一节和这一节中所示的代码,你可以把它们单独编译成一个组件,这样就可以在你的项目中不断的重用它们了。从下一节开始,我们将更深层次的介绍Attribute的应用,请继续关注。(待续)

原创粉丝点击