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

用于参数的Attribute

在编写多层应用程序的时候,你是否为每次要写大量类似的数据访问代码而感到枯燥无味?比如我们需要编写调用存储过程的代码,或者编写T_SQL代码,这些代码往往需要传递各种参数,有的参数个数比较多,一不小心还容易写错。有没有一种一劳永逸的方法?当然,你可以使用MS的Data Access Application Block,也可以使用自己编写的Block。这里向你提供一种另类方法,那就是使用Attribute。

下面的代码是一个调用AddCustomer存储过程的常规方法:

  1. public int AddCustomer(SqlConnection connection,    
  2.   
  3.         string customerName,    
  4.   
  5.         string country,    
  6.   
  7.         string province,    
  8.   
  9.         string city,    
  10.   
  11.         string address,    
  12.   
  13.         string telephone)   
  14.   
  15. {   
  16.   
  17.    SqlCommand command=new SqlCommand("AddCustomer", connection);   
  18.   
  19.    command.CommandType=CommandType.StoredProcedure;   
  20.   
  21.   
  22.   
  23.    command.Parameters.Add("@CustomerName",SqlDbType.NVarChar,50).Value=customerName;   
  24.   
  25.    command.Parameters.Add("@country",SqlDbType.NVarChar,20).Value=country;   
  26.   
  27.    command.Parameters.Add("@Province",SqlDbType.NVarChar,20).Value=province;   
  28.   
  29.    command.Parameters.Add("@City",SqlDbType.NVarChar,20).Value=city;   
  30.   
  31.    command.Parameters.Add("@Address",SqlDbType.NVarChar,60).Value=address;   
  32.   
  33.    command.Parameters.Add("@Telephone",SqlDbType.NvarChar,16).Value=telephone;   
  34.   
  35.    command.Parameters.Add("@CustomerId",SqlDbType.Int,4).Direction=ParameterDirection.Output;   
  36.   
  37.   
  38.   
  39.    connection.Open();   
  40.   
  41.    command.ExecuteNonQuery();   
  42.   
  43.    connection.Close();   
  44.   
  45.   
  46.   
  47.    int custId=(int)command.Parameters["@CustomerId"].Value;   
  48.   
  49.    return custId;   
  50.   
  51. }  
public int AddCustomer(SqlConnection connection, 

		string customerName, 

		string country, 

		string province, 

		string city, 

		string address, 

		string telephone)

{

   SqlCommand command=new SqlCommand("AddCustomer", connection);

   command.CommandType=CommandType.StoredProcedure;



   command.Parameters.Add("@CustomerName",SqlDbType.NVarChar,50).Value=customerName;

   command.Parameters.Add("@country",SqlDbType.NVarChar,20).Value=country;

   command.Parameters.Add("@Province",SqlDbType.NVarChar,20).Value=province;

   command.Parameters.Add("@City",SqlDbType.NVarChar,20).Value=city;

   command.Parameters.Add("@Address",SqlDbType.NVarChar,60).Value=address;

   command.Parameters.Add("@Telephone",SqlDbType.NvarChar,16).Value=telephone;

   command.Parameters.Add("@CustomerId",SqlDbType.Int,4).Direction=ParameterDirection.Output;



   connection.Open();

   command.ExecuteNonQuery();

   connection.Close();



   int custId=(int)command.Parameters["@CustomerId"].Value;

   return custId;

}

上面的代码,创建一个Command实例,然后添加存储过程的参数,然后调用ExecuteMonQuery方法执行数据的插入操作,最后返回CustomerId。从代码可以看到参数的添加是一种重复单调的工作。如果一个项目有100多个甚至几百个存储过程,作为开发人员的你会不会要想办法偷懒?(反正我会的:-))。

下面开始我们的代码自动生成工程:

我们的目的是根据方法的参数以及方法的名称,自动生成一个Command对象实例,第一步我们要做的就是创建一个SqlParameterAttribute, 代码如下:

  1. SqlCommandParameterAttribute.cs   
  2.   
  3.   
  4.   
  5. using System;   
  6.   
  7. using System.Data;   
  8.   
  9. using Debug=System.Diagnostics.Debug;   
  10.   
  11.   
  12.   
  13. namespace DataAccess   
  14.   
  15. {   
  16.   
  17.    // SqlParemeterAttribute 施加到存储过程参数   
  18.   
  19.    [ AttributeUsage(AttributeTargets.Parameter) ]   
  20.   
  21.    public class SqlParameterAttribute : Attribute   
  22.   
  23.    {   
  24.   
  25.       private string name;                      //参数名称   
  26.   
  27.       private bool paramTypeDefined;     //是否参数的类型已经定义   
  28.   
  29.       private SqlDbType paramType;       //参数类型   
  30.   
  31.       private int size;                  //参数尺寸大小   
  32.   
  33.       private byte precision;            //参数精度   
  34.   
  35.       private byte scale;                //参数范围   
  36.   
  37.       private bool directionDefined;     //是否定义了参数方向   
  38.   
  39.       private ParameterDirection direction;  //参数方向   
  40.   
  41.          
  42.   
  43.       public SqlParameterAttribute()   
  44.   
  45.       {   
  46.   
  47.       }   
  48.   
  49.          
  50.   
  51.       public string Name   
  52.   
  53.       {   
  54.   
  55.          get { return name == null ? string.Empty : name; }   
  56.   
  57.          set { _name = value; }   
  58.   
  59.       }   
  60.   
  61.          
  62.   
  63.       public int Size   
  64.   
  65.       {   
  66.   
  67.          get { return size; }   
  68.   
  69.          set { size = value; }   
  70.   
  71.       }   
  72.   
  73.          
  74.   
  75.       public byte Precision   
  76.   
  77.       {   
  78.   
  79.          get { return precision; }   
  80.   
  81.          set { precision = value; }   
  82.   
  83.       }   
  84.   
  85.          
  86.   
  87.       public byte Scale   
  88.   
  89.       {   
  90.   
  91.          get { return scale; }   
  92.   
  93.          set { scale = value; }   
  94.   
  95.       }   
  96.   
  97.          
  98.   
  99.       public ParameterDirection Direction   
  100.   
  101.       {   
  102.   
  103.          get  
  104.   
  105.          {   
  106.   
  107.             Debug.Assert(directionDefined);   
  108.   
  109.             return direction;   
  110.   
  111.          }   
  112.   
  113.          set  
  114.   
  115.          {   
  116.   
  117.             direction = value;    
  118.   
  119.             directionDefined = true;   
  120.   
  121.          }   
  122.   
  123.       }   
  124.   
  125.          
  126.   
  127.       public SqlDbType SqlDbType   
  128.   
  129.       {   
  130.   
  131.          get  
  132.   
  133.          {   
  134.   
  135.             Debug.Assert(paramTypeDefined);   
  136.   
  137.             return paramType;   
  138.   
  139.          }   
  140.   
  141.          set  
  142.   
  143.          {   
  144.   
  145.             paramType = value;   
  146.   
  147.             paramTypeDefined = true;   
  148.   
  149.          }   
  150.   
  151.       }   
  152.   
  153.          
  154.   
  155.       public bool IsNameDefined   
  156.   
  157.       {   
  158.   
  159.          get { return name != null && name.Length != 0; }   
  160.   
  161.       }   
  162.   
  163.          
  164.   
  165.       public bool IsSizeDefined   
  166.   
  167.       {   
  168.   
  169.          get { return size != 0; }   
  170.   
  171.       }   
  172.   
  173.          
  174.   
  175.       public bool IsTypeDefined   
  176.   
  177.       {   
  178.   
  179.          get { return paramTypeDefined; }   
  180.   
  181.       }   
  182.   
  183.          
  184.   
  185.       public bool IsDirectionDefined   
  186.   
  187.       {   
  188.   
  189.          get { return directionDefined; }   
  190.   
  191.       }   
  192.   
  193.          
  194.   
  195.       public bool IsScaleDefined   
  196.   
  197.       {   
  198.   
  199.          get { return _scale != 0; }   
  200.   
  201.       }   
  202.   
  203.          
  204.   
  205.       public bool IsPrecisionDefined   
  206.   
  207.       {   
  208.   
  209.          get { return _precision != 0; }   
  210.   
  211.       }   
  212.   
  213.          
  214.   
  215.       ...   
  216.   
  217.     
SqlCommandParameterAttribute.cs



using System;

using System.Data;

using Debug=System.Diagnostics.Debug;



namespace DataAccess

{

   // SqlParemeterAttribute 施加到存储过程参数

   [ AttributeUsage(AttributeTargets.Parameter) ]

   public class SqlParameterAttribute : Attribute

   {

      private string name;      				//参数名称

      private bool paramTypeDefined;     //是否参数的类型已经定义

      private SqlDbType paramType;       //参数类型

      private int size;                  //参数尺寸大小

      private byte precision;            //参数精度

      private byte scale;                //参数范围

      private bool directionDefined;     //是否定义了参数方向

      private ParameterDirection direction;  //参数方向

      

      public SqlParameterAttribute()

      {

      }

      

      public string Name

      {

         get { return name == null ? string.Empty : name; }

         set { _name = value; }

      }

      

      public int Size

      {

         get { return size; }

         set { size = value; }

      }

      

      public byte Precision

      {

         get { return precision; }

         set { precision = value; }

      }

      

      public byte Scale

      {

         get { return scale; }

         set { scale = value; }

      }

      

      public ParameterDirection Direction

      {

         get

         {

            Debug.Assert(directionDefined);

            return direction;

         }

         set

         {

            direction = value; 

		    directionDefined = true;

		 }

      }

      

      public SqlDbType SqlDbType

      {

         get

         {

            Debug.Assert(paramTypeDefined);

            return paramType;

         }

         set

         {

            paramType = value;

            paramTypeDefined = true;

         }

      }

      

      public bool IsNameDefined

      {

         get { return name != null && name.Length != 0; }

      }

      

      public bool IsSizeDefined

      {

         get { return size != 0; }

      }

      

      public bool IsTypeDefined

      {

         get { return paramTypeDefined; }

      }

      

      public bool IsDirectionDefined

      {

         get { return directionDefined; }

      }

      

      public bool IsScaleDefined

      {

         get { return _scale != 0; }

      }

      

      public bool IsPrecisionDefined

      {

         get { return _precision != 0; }

      }

      

      ...

  

以上定义了SqlParameterAttribute的字段和相应的属性,为了方便Attribute的使用,我们重载几个构造器,不同的重载构造器用于不用的参数:

  1. ...   
  2.   
  3.   
  4.   
  5.       // 重载构造器,如果方法中对应于存储过程参数名称不同的话,我们用它来设置存储过程的名称   
  6.   
  7.       // 其他构造器的目的类似   
  8.   
  9.       public SqlParameterAttribute(string name)   
  10.   
  11.       {   
  12.   
  13.          Name=name;   
  14.   
  15.       }   
  16.   
  17.   
  18.   
  19.       public SqlParameterAttribute(int size)   
  20.   
  21.       {   
  22.   
  23.          Size=size;   
  24.   
  25.       }   
  26.   
  27.          
  28.   
  29.       public SqlParameterAttribute(SqlDbType paramType)   
  30.   
  31.       {   
  32.   
  33.          SqlDbType=paramType;   
  34.   
  35.       }   
  36.   
  37.          
  38.   
  39.       public SqlParameterAttribute(string name, SqlDbType paramType)   
  40.   
  41.       {   
  42.   
  43.          Name = name;   
  44.   
  45.          SqlDbType = paramType;   
  46.   
  47.       }   
  48.   
  49.          
  50.   
  51.       public SqlParameterAttribute(SqlDbType paramType, int size)   
  52.   
  53.       {   
  54.   
  55.          SqlDbType = paramType;   
  56.   
  57.          Size = size;   
  58.   
  59.       }   
  60.   
  61.          
  62.   
  63.          
  64.   
  65.       public SqlParameterAttribute(string name, int size)   
  66.   
  67.       {   
  68.   
  69.          Name = name;   
  70.   
  71.          Size = size;   
  72.   
  73.       }   
  74.   
  75.          
  76.   
  77.       public SqlParameterAttribute(string name, SqlDbType paramType, int size)   
  78.   
  79.       {   
  80.   
  81.          Name = name;   
  82.   
  83.          SqlDbType = paramType;   
  84.   
  85.          Size = size;   
  86.   
  87.       }   
  88.   
  89.    }   
  90.   
  91. }  
...



      // 重载构造器,如果方法中对应于存储过程参数名称不同的话,我们用它来设置存储过程的名称

      // 其他构造器的目的类似

      public SqlParameterAttribute(string name)

      {

         Name=name;

      }



      public SqlParameterAttribute(int size)

      {

         Size=size;

      }

      

      public SqlParameterAttribute(SqlDbType paramType)

      {

         SqlDbType=paramType;

      }

      

      public SqlParameterAttribute(string name, SqlDbType paramType)

      {

         Name = name;

         SqlDbType = paramType;

      }

      

      public SqlParameterAttribute(SqlDbType paramType, int size)

      {

         SqlDbType = paramType;

         Size = size;

      }

      

      

      public SqlParameterAttribute(string name, int size)

      {

         Name = name;

         Size = size;

      }

      

      public SqlParameterAttribute(string name, SqlDbType paramType, int size)

      {

         Name = name;

         SqlDbType = paramType;

         Size = size;

      }

   }

}

为了区分方法中不是存储过程参数的那些参数,比如SqlConnection,我们也需要定义一个非存储过程参数的Attribute:

  1. //NonCommandParameterAttribute.cs   
  2.   
  3.   
  4.   
  5. using System;   
  6.   
  7. namespace DataAccess   
  8.   
  9. {   
  10.   
  11.    [ AttributeUsage(AttributeTargets.Parameter) ]   
  12.   
  13.    public sealed class NonCommandParameterAttribute : Attribute   
  14.   
  15.    {   
  16.   
  17.    }   
  18.   
  19. }  
//NonCommandParameterAttribute.cs



using System;

namespace DataAccess

{

   [ AttributeUsage(AttributeTargets.Parameter) ]

   public sealed class NonCommandParameterAttribute : Attribute

   {

   }

}

我们已经完成了SQL的参数Attribute的定义,在创建Command对象生成器之前,让我们考虑这样的一个事实,那就是如果我们数据访问层调用的不是存储过程,也就是说Command的CommandType不是存储过程,而是带有参数的SQL语句,我们想让我们的方法一样可以适合这种情况,同样我们仍然可以使用Attribute,定义一个用于方法的Attribute来表明该方法中的生成的Command的CommandType是存储过程还是SQL文本,下面是新定义的Attribute的代码:

  1. //SqlCommandMethodAttribute.cs   
  2.   
  3.   
  4.   
  5. using System;   
  6.   
  7. using System.Data;   
  8.   
  9.   
  10.   
  11. namespace Emisonline.DataAccess   
  12.   
  13. {   
  14.   
  15.    [AttributeUsage(AttributeTargets.Method)]   
  16.   
  17.    public sealed class SqlCommandMethodAttribute : Attribute   
  18.   
  19.    {   
  20.   
  21.       private string commandText;   
  22.   
  23.       private CommandType commandType;   
  24.   
  25.   
  26.   
  27.       public SqlCommandMethodAttribute( CommandType commandType, string commandText)   
  28.   
  29.       {   
  30.   
  31.          commandType=commandType;   
  32.   
  33.          commandText=commandText;   
  34.   
  35.       }   
  36.   
  37.   
  38.   
  39.       public SqlCommandMethodAttribute(CommandType commandType) : this(commandType, null){}   
  40.   
  41.   
  42.   
  43.       public string CommandText   
  44.   
  45.       {   
  46.   
  47.          get  
  48.   
  49.          {   
  50.   
  51.             return commandText==null ? string.Empty : commandText;   
  52.   
  53.          }   
  54.   
  55.          set  
  56.   
  57.          {   
  58.   
  59.             commandText=value;   
  60.   
  61.          }   
  62.   
  63.       }   
  64.   
  65.   
  66.   
  67.       public CommandType CommandType   
  68.   
  69.       {   
  70.   
  71.          get  
  72.   
  73.          {   
  74.   
  75.              return commandType;   
  76.   
  77.          }   
  78.   
  79.          set  
  80.   
  81.          {   
  82.   
  83.             commandType=value;   
  84.   
  85.          }   
  86.   
  87.       }   
  88.   
  89.    }   
  90.   
  91. }  
//SqlCommandMethodAttribute.cs



using System;

using System.Data;



namespace Emisonline.DataAccess

{

   [AttributeUsage(AttributeTargets.Method)]

   public sealed class SqlCommandMethodAttribute : Attribute

   {

      private string commandText;

      private CommandType commandType;



      public SqlCommandMethodAttribute( CommandType commandType, string commandText)

      {

         commandType=commandType;

         commandText=commandText;

      }



      public SqlCommandMethodAttribute(CommandType commandType) : this(commandType, null){}



      public string CommandText

      {

         get

         {

            return commandText==null ? string.Empty : commandText;

         }

         set

         {

            commandText=value;

         }

      }



      public CommandType CommandType

      {

         get

         {

             return commandType;

         }

         set

         {

            commandType=value;

         }

      }

   }

}



我们的Attribute的定义工作已经全部完成,下一步就是要创建一个用来生成Command对象的类。(待续)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值