(转)简单代码生成器原理剖析(二)
原文地址:http://www.cnblogs.com/OceanEyes/archive/2012/03/08/codebuilder.html
上篇《简单代码生成器原理剖析(一)》分析了代码生成器的原理,查询数据库系统视图:INFORMATION_SCHEMA.TABLES、 INFORMATION_SCHEMA.COLUMNS 可以获得数据库中表、列的相关信息,再运用StringBuilder类的其AppendLine方法追加字符串,最后早运用File.WriteAllText方法将字符串写入文件。
第二版代码生成器在第一版的基础上扩展了以下功能:
- 使用了部分类(partial):当使用大项目或自动生成的代码(如由 Windows 窗体设计器提供的代码)时,将一个类、结构或接口类型拆分到多个文件中的做法就很有用。 分部类型可能包含分部方法。
- 使用可空类型:由于数据库中表中数据很有可能是NULL,可空类型使得数据从表中读取出来赋值给值类型更加兼容。
- 增加了ToModel方法:将数据库表中一行数据封装成Model类的对象返回。
/// <summary>/// Model/// </summary> public static void CreateModel(CodeBuilderArgs args,string tableName) { DataTable dt = ExecuteDataTable(args.ConnectionString, "select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@TABLE_NAME" ,new SqlParameter("TABLE_NAME",tableName)); StringBuilder sb = new StringBuilder(); sb.AppendLine("using System;"); sb.AppendLine("using System.Collections.Generic;"); sb.AppendLine("using System.Linq;"); sb.AppendLine("using System.Text;"); sb.AppendLine("namespace " + args .Namespace+ ".Model"); sb.AppendLine("{"); sb.AppendLine("partial class " + tableName); sb.AppendLine("{");foreach (DataRow row in dt.Rows) {string colName = Convert.ToString(row["COLUMN_NAME"]);string colType = Convert.ToString(row["DATA_TYPE"]); Type netType = GetTypeByDBType(colType);string netTypeName;if (netType.IsValueType) { netTypeName = netType + "?"; }else { netTypeName = netType.ToString(); } sb.AppendLine("public " +netTypeName +" "+ colName + " { get; set; }"); } sb.AppendLine(" }"); sb.AppendLine(" }");string modelDir = Path.Combine(args.OutputDir, "Model");string modelFile = Path.Combine(modelDir, tableName+".cs"); Directory.CreateDirectory(modelDir); File.WriteAllText(modelFile, sb.ToString()); }
/// <summary>///DAL/// </summary>/// <param name="args"></param>/// <param name="tableName"></param> public static void CreateDAL(CodeBuilderArgs args, string tableName) { StringBuilder sb = new StringBuilder(); DataTable dt = ExecuteDataTable(args.ConnectionString, "select * from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME=@TABLE_NAME" , new SqlParameter("TABLE_NAME", tableName)); sb.AppendLine("using System;"); sb.AppendLine("using System.Collections.Generic;"); sb.AppendLine("using System.Linq;"); sb.AppendLine("using System.Text;"); sb.AppendLine("using "+args.Namespace+".Model;"); sb.AppendLine("using System.Data.SqlClient;"); sb.AppendLine("using System.Data;"); sb.AppendLine("namespace "+args.Namespace+".DAL"); sb.AppendLine("{"); sb.AppendLine("partial class "+tableName+"DAL"); sb.AppendLine("{"); sb.AppendLine("public int AddNew("+tableName+" model)"); sb.AppendLine("{"); string[] cols = GetColsWithoutId(GetCols(dt, new List<string>())).ToArray();var colsParameters=from e in cols select"@"+ e; sb.AppendLine("string sql = \"insert into " + tableName + "(" + string.Join(",", cols) + ") output inserted.id values(" + string.Join(",", colsParameters.ToArray()) + ")\";"); sb.AppendLine("int id = (int)SqlHelper.ExecuteScalar(sql"); foreach (DataRow row in dt.Rows) {string colName = Convert.ToString(row["COLUMN_NAME"]);if(!(colName.ToLower()=="id")) { sb.AppendLine(", new SqlParameter(\""+colName+"\", model."+colName+")"); } } sb.AppendLine(");"); sb.AppendLine("return id;"); sb.AppendLine("}"); var par=from e in cols select e+"="+"@"+e; sb.AppendLine("public bool Update("+tableName+" model)"); sb.AppendLine("{"); sb.AppendLine("string sql = \"update "+tableName+" set "+string.Join(",",par.ToArray())+" where id=@id\";"); sb.AppendLine("int rows = SqlHelper.ExecuteNonQuery(sql");foreach (DataRow row in dt.Rows) {string colName = Convert.ToString(row["COLUMN_NAME"]); sb.AppendLine(", new SqlParameter(\"" + colName + "\", model." + colName + ")"); } sb.AppendLine(");"); sb.AppendLine("return rows>0;"); sb.AppendLine("}"); sb.AppendLine("public bool Delete(int id)"); sb.AppendLine("{"); sb.AppendLine("int rows = SqlHelper.ExecuteNonQuery(\"delete from "+tableName+" where id=@id\","); sb.AppendLine("new SqlParameter(\"id\", id));"); sb.AppendLine("return rows > 0;"); sb.AppendLine("}"); sb.AppendLine("private static "+tableName+" ToModel(DataRow row)"); sb.AppendLine("{"); sb.AppendLine(""+tableName+" model = new "+tableName+"();");foreach (DataRow row in dt.Rows) {string colName = Convert.ToString(row["COLUMN_NAME"]);string colType = Convert.ToString(row["DATA_TYPE"]); Type netType = GetTypeByDBType(colType);string netTypeName;if (netType.IsValueType) { netTypeName = netType + "?"; }else { netTypeName = netType.ToString(); } sb.AppendLine("model."+colName+" = row.IsNull(\""+colName+"\") ? null : "+"("+netTypeName+")"+"row[\""+colName+"\"];"); } sb.AppendLine("return model;"); sb.AppendLine("}"); // sb.AppendLine("public "+tableName+" Get(int id)"); sb.AppendLine("{"); sb.AppendLine("DataTable dt = SqlHelper.ExecuteDataTable(\"select * from "+tableName+" where id=@id\","); sb.AppendLine("new SqlParameter(\"id\", id));"); sb.AppendLine("if(dt.Rows.Count > 1)"); sb.AppendLine("{"); sb.AppendLine("throw new Exception(\"more than 1 row was found\");"); sb.AppendLine("}"); sb.AppendLine("if(dt.Rows.Count <= 0)"); sb.AppendLine("{"); sb.AppendLine("return null; "); sb.AppendLine("}"); sb.AppendLine("DataRow row = dt.Rows[0];"); sb.AppendLine(""+tableName+" model = ToModel(row);"); sb.AppendLine("return model;"); sb.AppendLine("}"); sb.AppendLine("public IEnumerable<"+tableName+">ListAll()"); sb.AppendLine("{"); sb.AppendLine("List<"+tableName+"> list = new List<"+tableName+">();"); sb.AppendLine("DataTable dt = SqlHelper.ExecuteDataTable(\"select * from "+tableName+"\");"); sb.AppendLine("foreach (DataRow row in dt.Rows)"); sb.AppendLine("{"); sb.AppendLine("list.Add(ToModel(row));"); sb.AppendLine("}"); sb.AppendLine("return list;"); sb.AppendLine("}"); sb.AppendLine("}"); sb.AppendLine("}"); string DALlDir = Path.Combine(args.OutputDir,"DAL");string DALFile = Path.Combine(DALlDir,tableName+"DAL.cs"); Directory.CreateDirectory(DALlDir); File.WriteAllText(DALFile,sb.ToString()); }private static IEnumerable<string> GetColsWithoutId(List<string> cols) {var colArray = from col in cols where col.ToLower() != "id" select col;return colArray; }private static List<string> GetCols(DataTable dt, List<string> cols) {foreach (DataRow row in dt.Rows) {string colName = Convert.ToString(row["COLUMN_NAME"]); cols.Add(colName); }return cols; }
/// <summary>/// BLL/// </summary>/// <param name="args"></param>/// <param name="tableName"></param> public static void CreateBLL(CodeBuilderArgs args,string tableName) { StringBuilder sb = new StringBuilder(); sb.AppendLine("using System;"); sb.AppendLine("using System.Collections.Generic;"); sb.AppendLine("using System.Linq;"); sb.AppendLine("using System.Text;"); sb.AppendLine("using "+args.Namespace+".Model;"); sb.AppendLine("using "+args.Namespace+".DAL;"); sb.AppendLine("namespace "+args.Namespace+".BLL"); sb.AppendLine("{"); sb.AppendLine("partial class "+tableName+"BLL"); sb.AppendLine("{"); sb.AppendLine("public int AddNew("+tableName+" model)"); sb.AppendLine("{"); sb.AppendLine("return new "+tableName+"DAL().AddNew(model);"); sb.AppendLine("}"); sb.AppendLine("public bool Delete(int id)"); sb.AppendLine("{"); sb.AppendLine("return new "+tableName+"DAL().Delete(id);"); sb.AppendLine("}"); sb.AppendLine("public bool Update("+tableName+" model)"); sb.AppendLine("{"); sb.AppendLine("return new "+tableName+"DAL().Update(model);"); sb.AppendLine("}"); sb.AppendLine("public "+tableName+" Get(int id)"); sb.AppendLine("{"); sb.AppendLine("return new "+tableName+"DAL().Get(id);"); sb.AppendLine("}"); sb.AppendLine("public IEnumerable<"+tableName+"> ListAll()"); sb.AppendLine("{"); sb.AppendLine("return new "+tableName+"DAL().ListAll();"); sb.AppendLine("}"); sb.AppendLine("}"); sb.AppendLine("}");string BLLDir = Path.Combine(args.OutputDir,"BLL");string BLLFile = Path.Combine(BLLDir,tableName+"BLL.cs"); Directory.CreateDirectory(BLLDir); File.WriteAllText(BLLFile,sb.ToString()); }
转载于:https://www.cnblogs.com/fcsh820/archive/2012/03/15/2398470.html
(转)简单代码生成器原理剖析(二)相关推荐
- 简单代码生成器原理剖析(一)
上篇文章(深入浅出三层架构)分析了简单三层架构的实现.包括Model,DAL(数据访问层),BLL(业务逻辑层)的实现. 实际开发中,由于重复代码的操作,会花费大量时间,如果以代码生成器来自动生成三层 ...
- 【es】es 分布式一致性原理剖析(二)-Meta篇
1.概述 转载:Elasticsearch分布式一致性原理剖析(二)-Meta篇 前言 "Elasticsearch分布式一致性原理剖析"系列将会对Elasticsearch的分布 ...
- super函数没有那么简单-super原理剖析
开始之前,先出一道题: 1 #super函数探讨 2 class A(object): 3 def __init__(self): 4 print 'A.__init__' 5 6 class B(A ...
- iPhone/Mac Objective-C内存管理教程和原理剖析(二)口诀与范式转
版权声明 此文版权归作者Vince Yuan (vince.yuan#gmail.com)所有.欢迎非营利性转载,转载时必须包含原始链接http://vinceyuan.cnblogs.com,且必须 ...
- 一致性Hash(Consistent Hashing)原理剖析及Java实现
目录 一.一致性Hash(Consistent Hashing)原理剖析 二.一致性hash算法的Java实现 一.一致性Hash(Consistent Hashing)原理剖析 引入 一致性哈希算法 ...
- [转] 深入探讨PageRank(二):PageRank原理剖析
深入探讨PageRank(二):PageRank原理剖析 关于PageRank的基础知识简介请参见博文:<深入探讨PageRank(一):PageRank算法原理入门>. http://b ...
- fastText的原理剖析
fastText的原理剖析 1. fastText的模型架构 fastText的架构非常简单,有三层:输入层.隐含层.输出层(Hierarchical Softmax) 输入层:是对文档embeddi ...
- 统计学习方法|支持向量机(SVM)原理剖析及实现
欢迎直接到我的博客查看最近文章:www.pkudodo.com.更新会比较快,评论回复我也能比较快看见,排版也会更好一点. 原始blog链接: http://www.pkudodo.com/2018/ ...
- 统计学习方法|逻辑斯蒂原理剖析及实现
欢迎直接到我的博客查看最近文章:www.pkudodo.com.更新会比较快,评论回复我也能比较快看见,排版也会更好一点. 原始blog链接: http://www.pkudodo.com/2018/ ...
最新文章
- 学习笔记TF065:TensorFlowOnSpark
- 几句代码 修改 Kali 2020.3 - root 用户的密码
- 爱情这东西,真的有报应吗…
- Jquery的事件操作和文档操作
- python实现不重复排列组合_Python实现输入字符串,返回其任意排列组合
- boost::owner_less相关的测试程序
- 你和女朋友的婚后老年生活!
- ajax异步监控_监控整页(非AJAX),需要通知
- android create命令,phonegap运行android – create命令失败,退出代码8 – linux
- eclipse 安装插件不生效
- 软件再快不如自带:找不到电脑文件?教你这 3 个Mac搜索技巧
- 通信与信息系统专业排名全国前十的…
- 康佳电视android,康佳电视怎么连接手机 康佳电视连接手机步骤【图文介绍】
- 什么?阿里巴巴不允许工程师直接使用Log4j和Logback的API!
- 行走在数据库上的行癫(三)
- 企业建站有必要使用高防服务器吗?
- 牛X公司的开会方式,明天开始参照执行
- Go string类型及其使用
- oracle中怎么判断为周五,求一年中所有星期五的日期
- 频遭攻击 索尼无奈关闭多国网站