Attribute在.NET编程中的应用(三),Attribut,ttribute,tribute在,ribute在.,ibute在.N,bute在.NE,ute在.NET,te在.NET编,e在.NET编程,在.NET编程中,.NET编程中的,NET编程中的应,ET编程中的应用,T编程中的应用(,编程中的应用(三

本站地址:http://www.bajiao123.com

Attribute在.NET编程中的应用(三)
在编写多层应用程序的时候,你是否为每次要写大量类似的数据访问代码而感到枯燥无味?比如我们需要编写调用存储过程的代码,或者编写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; }
se
本站地址:http://www.bajiao123.com

