用于参数的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.csusing 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.csusing System;namespace DataAccess{   [ AttributeUsage(AttributeTargets.Parameter) ]   public sealed class NonCommandParameterAttribute : Attribute   {   }}

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

//SqlCommandMethodAttribute.csusing 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对象的类。(待续)

SqlCommandGenerator类的设计

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

引用的命名空间:

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

类代码:

namespace DataAccess{   public sealed class SqlCommandGenerator   {      //私有构造器,不允许使用无参数的构造器构造一个实例      private SqlCommandGenerator()      {         throw new NotSupportedException();      }      //静态只读字段,定义用于返回值的参数名称      public static readonly string ReturnValueParameterName = "RETURN_VALUE";      //静态只读字段,用于不带参数的存储过程      public static readonly object[] NoValues = new object[] {};               public static SqlCommand GenerateCommand(SqlConnection connection,                                  MethodInfo method, object[] values)      {         //如果没有指定方法名称,从堆栈帧得到方法名称         if (method == null)             method = (MethodInfo) (new StackTrace().GetFrame(1).GetMethod());         // 获取方法传进来的SqlCommandMethodAttribute         // 为了使用该方法来生成一个Command对象,要求有这个Attribute。         SqlCommandMethodAttribute commandAttribute =             (SqlCommandMethodAttribute) Attribute.GetCustomAttribute(method, typeof(SqlCommandMethodAttribute));         Debug.Assert(commandAttribute != null);         Debug.Assert(commandAttribute.CommandType == CommandType.StoredProcedure ||       commandAttribute.CommandType == CommandType.Text);         // 创建一个SqlCommand对象,同时通过指定的attribute对它进行配置。         SqlCommand command = new SqlCommand();         command.Connection = connection;         command.CommandType = commandAttribute.CommandType;               // 获取command的文本,如果没有指定,那么使用方法的名称作为存储过程名称          if (commandAttribute.CommandText.Length == 0)         {            Debug.Assert(commandAttribute.CommandType == CommandType.StoredProcedure);            command.CommandText = method.Name;         }         else         {            command.CommandText = commandAttribute.CommandText;         }         // 调用GeneratorCommandParameters方法,生成command参数,同时添加一个返回值参数         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)      {         // 得到所有的参数,通过循环一一进行处理。                  ParameterInfo[] methodParameters = method.GetParameters();         int paramIndex = 0;         foreach (ParameterInfo paramInfo in methodParameters)         {            // 忽略掉参数被标记为[NonCommandParameter ]的参数                     if (Attribute.IsDefined(paramInfo, typeof(NonCommandParameterAttribute)))               continue;                        // 获取参数的SqlParameter attribute,如果没有指定,那么就创建一个并使用它的缺省设置。            SqlParameterAttribute paramAttribute = (SqlParameterAttribute) Attribute.GetCustomAttribute(     paramInfo, typeof(SqlParameterAttribute));         if (paramAttribute == null)         paramAttribute = new SqlParameterAttribute();            //使用attribute的设置来配置一个参数对象。使用那些已经定义的参数值。如果没有定义,那么就从方法       // 的参数来推断它的参数值。      SqlParameter 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.Precision = paramAttribute.Precision;                        if (paramAttribute.IsDirectionDefined)            {               sqlParameter.Direction = paramAttribute.Direction;            }            else            {               if (paramInfo.ParameterType.IsByRef)               {                  sqlParameter.Direction = paramInfo.IsOut ?                               ParameterDirection.Output :                               ParameterDirection.InputOutput;               }               else               {                  sqlParameter.Direction = ParameterDirection.Input;               }            }                     // 检测是否提供的足够的参数对象值     Debug.Assert(paramIndex < values.Length);                      //把相应的对象值赋于参数。           sqlParameter.Value = values[paramIndex];           command.Parameters.Add(sqlParameter);                                               paramIndex++;         }               //检测是否有多余的参数对象值         Debug.Assert(paramIndex == values.Length);      }   }}

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

重构新的AddCustomer代码:

[ 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; //需要初始化输出参数  //调用Command生成器生成SqlCommand实例   SqlCommand command = SqlCommandGenerator.GenerateCommand( connection, null, new object[]{customerName,country,province,city,address,telephone,customerId } );                            connection.Open();   command.ExecuteNonQuery();   connection.Close();   //必须明确返回输出参数的值   customerId=(int)command.Parameters["@CustomerId"].Value;}

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

Attribute在.NET编程中的应用(三)的更多相关文章

  1. Attribute在.net编程中的应用

    Attribute FYI Link: Attribute在.net编程中的应用(一) Attribute在.net编程中的应用(二) Attribute在.net编程中的应用(三) Attribut ...

  2. (转)Attribute在.net编程中的应用

    Attribute在.net编程中的应用(一)Attribute的基本概念 经常有朋友问,Attribute是什么?它有什么用?好像没有这个东东程序也能运行.实际上在.Net中,Attribute是一 ...

  3. [转]Attribute在.net编程中的应用

    Attribute在.net编程中的应用(一) Attribute的基本概念 经常有朋友问,Attribute是什么?它有什么用?好像没有这个东东程序也能运行.实际上在.Net中,Attribute是 ...

  4. Attribute在.net编程中的应用(一)

    Attribute的基本概念 经常有朋友问,Attribute是什么?它有什么用?好像没有这个东东程序也能运行.实际上在.Net中,Attribute是一个非常重要的组成部分,为了帮助大家理解和掌握A ...

  5. 【Java并发编程】6、volatile关键字解析&内存模型&并发编程中三概念

    volatile这个关键字可能很多朋友都听说过,或许也都用过.在Java 5之前,它是一个备受争议的关键字,因为在程序中使用它往往会导致出人意料的结果.在Java 5之后,volatile关键字才得以 ...

  6. shell编程中的 三种结构: 条件if/选择结构case/循环for/while/until等结构 和 函数的用法

    shell 函数的使用 (md中, 列表本身是有格式的, 他要产生缩进, 其次,列表项和列表项之间, 可以留有一个空行, 是合法的, 允许的) shell函数,就是 就相当于一个命令来看待和处理的, ...

  7. iOS:网络编程中三个数据解析协议HTTP、XML、JSON的详细介绍

    网络编程:HTTP协议.XML数据协议.JSON数据协议: HTTP: 1.HTTP传输数据有四种方式:Get方式.Post方式.同步请求方式.异步请求方式. 说明:同步和异步请求方式在创建链接对象和 ...

  8. volatile关键字解析&内存模型&并发编程中三概念

    原文链接: http://www.cnblogs.com/dolphin0520/p/3920373.html volatile这个关键字可能很多朋友都听说过,或许也都用过.在Java5之前,它是一个 ...

  9. Java编程中的一些常见问题汇总

    转载自  http://macrochen.iteye.com/blog/1393502 每天在写Java程序,其实里面有一些细节大家可能没怎么注意,这不,有人总结了一个我们编程中常见的问题.虽然一般 ...

随机推荐

  1. 【转】 中兴OLT-C300常用命令

    中兴OLT C300show running-config (加载各种板卡)show gpon onu uncfg (查看OLT所有未配置的ONU)show gpon onu uncfg gpon-o ...

  2. ubuntu 11.04侧边栏怎么添加图标

    打开想添加的软件,图标会出现在侧边栏,右击之,点Keep In Launcher即可

  3. SAP 条形码

    使用系统生成的条形码 正常的排列;将扫描由左到右.旋转对齐将从上到下扫描90度倒立定线将扫描所180度从右到左底部对齐将从底部到顶部270度扫描 但在实际应用中,条形码的大小不仅与此处有关,也与字符格 ...

  4. 将 C# 枚举反序列化为 JSON 字符串 实践

    一.定义枚举 public enum SiteTypeEnum { 中转部 = 1, 网点 = 2 } 还有 BooleanEnum 和 OptTypeEnum 这两个枚举,这里暂且省略了它们的定义. ...

  5. 移动端效果之IndexList

    写在前面 接着前面的移动端效果讲,这次讲解的的是IndexList的实现原理.效果如下: 代码请看这里:github 移动端效果之swiper 移动端效果之picker 移动端效果之cellSwipe ...

  6. C语言 实现base64

    #include <stdio.h> const char base[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvw ...

  7. UVa127,"Accordian" Patience

    注意1堆的时候,pile后面没有s!!!!因为这个WA了一次,否则就1A了 犯了一个很幼稚很幼稚的错误,申请ans[]后玩了吧ans置0,结果调了好长好长时间,本来是敲完就能过的T T啊啊啊啊啊啊,一 ...

  8. WPF ListBox 一些小知识点

    页面代码: <Grid Grid.Row="0" Grid.Column="2"> <ListBox x:Name="lvStep& ...

  9. Eclipse中Hibernate插件的安装

    在使用Hibernate开发时,大多数情况下涉及到其XML配置文件的编辑,尤其是.cfg.xml(配置文件)和hbm.xml(关系映射文件)这两种.为了更方便的使用此框架,其插件的安装是很有必要的. ...

  10. 基于vip和twemproxy代理实现redis集群的无感知弹性扩容

    目标是实现redis集群的无感知弹性扩容 关键点 1是无感知,即对redis集群的用户来说服务ip和port保持不变 2.弹性扩容,指的是在需要时刻可以按照业务扩大redis存储容量. 最原始的twe ...