2016-02-23 09:37:58
Attribute在.NET编程中的应用(四)
SqlCommandGenerator类的设计
SqlCommandGEnerator类的设计思路就是通过反射得到方法的参数,使用被SqlCommandParameterAttribute标记的参数来装配一个Command实例。
引用的命名空间:
//SqlCommandGenerator.cs using 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的应用,请继续关注。(待续)
相关推荐
猜你还喜欢这些内容,不妨试试阅读一下评论与留言
以下内容均由网友提交发布,版权与真实性无法查证,请自行辨别。微信订阅号
扫码关注「任霏博客」微信订阅号内容标签
最新留言
- 你写得非常清晰明了,让我很容易理解你的观点。
- 感谢分享!拿走了~
- 您是说 UCClient 类接收来自Discuz的UCenter的消息吧,请求是来自 Discuz 的 UCenter吗?code 为 null 说明请求URL地址中没有 code 参数 (?code=xxx) ,确定是 UCenter 发起的请求吗?
- String code = request.getParameter("code"); code一直是null 这是为什么啊
- 你好,我想问一下如果是分析型的数据库要怎么制作docker镜像呢 是修改V008R003C002B0320版本号吗
- 可以的,我也正在开发分享的程序,可以邮件或群联系我都可以,关于页面里有联系方式:https://www.renfei.net/page/about 。
- 有破解软件的需要可以私下联系您吗?
- 您好,手机APP只是个客户端,用于数据呈现展示,数据均保存在服务器上,只留个APP没有任何用处,无能为力哦。
- 老哥 看你弄了这么多软件好厉害啊。 我有个软件 我买过几个小会员 没用几天 然后商家跑路了,软件服务器关闭了,连不上去 用不了。 你能做成一个打补丁版本可以本地用的么? 方便看下么?https://haodezhe.lanzouw.com/iD0f30h9joza 谢谢老哥!
- 您好,由于版权投诉和我国知识产权法的完善,我已经下架所有破解软件的下载链接了。
热文排行
- 生花妙笔信手来 – 基于 Amazon SageMaker 使用 Grounded-SAM 加速电商广告素材生成 [1]
- github.renfei.net 不再完整代理 Github 页面改为代理指定文件
- 优雅的源代码管理(三):本地优雅的使用 Git Rebase 变基
- 优雅的源代码管理(二):Git 的工作原理
- 优雅的源代码管理(一):版本控制系统 VCS(Version Control System)与软件配置管理 SCM(Software Configuration Management)
- ChatGPT 开发商 OpenAI 买下极品域名 AI.com
- 火爆的 AI 人工智能 ChatGPT 国内注册教程、使用方式和收费标准
- 解决 SpringCloud 中 bootstrap.yml 不识别 @activatedProperties@ 参数
- Cron表达式书写教程搞定Linux、Spring、Quartz的定时任务
- 阿里云香港可用区C发生史诗级故障