Attribute在.NET編程中的應用(三)

Attribute在.NET編程中的應用(三)

用於參數的Attribute

在編寫多層應用程序的時候,你是否爲每次要寫大量類似的數據訪問代碼而感到枯燥無味?比如我們需要編寫調用存儲過程的代碼,或者編寫T_SQL代碼,這些代碼往往需要傳遞各種參數,有的參數個數比較多,一不小心還容易寫錯。有沒有一種一勞永逸的方法?當然,你可以使用MS的Data Access Application Block,也可以使用自己編寫的Block。這裏向你提供一種另類方法,那就是使用Attribute。

下面的代碼是一個調用AddCustomer存儲過程的常規方法:

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, 代碼如下:

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的使用,我們重載幾個構造器,不同的重載構造器用於不用的參數:
      ...

      // 重載構造器,如果方法中對應於存儲過程參數名稱不同的話,我們用它來設置存儲過程的名稱
      // 其他構造器的目的類似
      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:

//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的代碼:

//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對象的類。(待續)

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章