使用Easy4net编写代码生成器
在项目中经常要手动创建和数据库对应的实体类,如果数据库表比较多或者表字段比较多,那会是一个工作量非常大的事情,所以我根据自己的需求写了一个简单的代码生成工具,工具使用Easy4net框架开发。
下面是代码目录结构:
项目开始预备步骤:
1. 创建项目EntityCodeBuilder
2. 引入Easy4net项目源码
3. 创建Entity类库
4. 创建TableName和TableColumn类
5. 在App.config配置文件中配置数据库连接信息
TableName源码:
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace EntityCodeBuilder.Entity { public class TableName { public string Name { get; set; } } }
TableColumn源码:
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace EntityCodeBuilder.Entity { public class TableColumn { public string Name { get; set; } public string Type { get; set; } public string IsIdentity { get; set; } public string IsPrimaryKey { get; set; } public string IsNull { get; set; } } }
App.config配置文件代码:
<appSettings> <add key="DbType" value="sqlserver"/> <add key="connectionString" value="Data Source=.;Initial Catalog=test;User ID=test;Password=test123;Trusted_Connection=no;Min Pool Size=10;Max Pool Size=100;"/> <!--<add key="DbType" value="mysql"/> <add key="connectionString" value="Data Source=.;port=8001;User ID=test;Password=123456;DataBase=test;Min Pool Size=10;Max Pool Size=100;"/>--> </appSettings>
UI上的代码不细说了,主要是有几个类的代码:
TableHelper中的代码,获取数据库所有表名:
/// <summary> /// 获取数据库所有表名 /// </summary> /// <param name="connection"></param> /// <returns></returns> public static List<TableName> GetTables() { SqlConnection connection = (SqlConnection)DbFactory.CreateDbConnection(AdoHelper.ConnectionString); List<TableName> tablelist = new List<TableName>(); try { if (connection.State == ConnectionState.Closed) { connection.Open(); DataTable objTable = connection.GetSchema("Tables"); foreach (DataRow row in objTable.Rows) { TableName tb = new TableName(); tb.Name = row[2].ToString(); tablelist.Add(tb); } } } catch(Exception e) { throw e; } finally { if (connection != null && connection.State == ConnectionState.Closed) { connection.Dispose(); } } return tablelist; }
TableHelper中的代码,根据表名获取所有列:
/// <summary> /// 获取字段 /// </summary> /// <param name="connection"></param> /// <param name="TableName"></param> /// <returns></returns> public static List<TableColumn> GetColumnField(string TableName) { StringBuilder sb = new StringBuilder(); sb.Append(" SELECT a.name,"); sb.Append(" b.name as type,"); sb.Append(" CASE COLUMNPROPERTY(a.id,a.name,‘IsIdentity‘) WHEN 1 THEN ‘√‘ ELSE ‘‘ END as IsIdentity, "); sb.Append(" CASE WHEN EXISTS ( SELECT * FROM sysobjects WHERE xtype=‘PK‘ AND name IN ( SELECT name FROM sysindexes WHERE id=a.id AND indid IN ( SELECT indid FROM sysindexkeys "); sb.Append(" WHERE id=a.id AND colid IN ( SELECT colid FROM syscolumns WHERE id=a.id AND name=a.name ) ) ) ) THEN ‘√‘ ELSE ‘‘ END as IsPrimaryKey,"); sb.Append(" CASE a.isnullable WHEN 1 THEN ‘√‘ ELSE ‘‘ END as IsNull "); sb.Append(" FROM syscolumns a "); sb.Append(" LEFT JOIN systypes b ON a.xtype=b.xusertype "); sb.Append(" INNER JOIN sysobjects c ON a.id=c.id AND c.xtype=‘U‘ AND c.name<>‘dtproperties‘ "); sb.Append(" LEFT JOIN syscomments d ON a.cdefault=d.id "); sb.Append(" WHERE c.name = ‘").Append(TableName).Append("‘ "); sb.Append(" ORDER BY c.name, a.colorder"); //使用Easy4net框架查询数据 List<TableColumn> list = db.FindBySql<TableColumn>(sb.ToString()); return list; }
知道表名,字段名称,字段类型后,要生成实体类,需要根据数据库中的数据类型转换为C#中的类型:
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace WindowsDemo { public class TypeHelper { public static string GetType(string type) { string newType = "String"; switch (type) { case "varchar": case "varchar2": case "nvarchar": case "char": newType = "String"; break; case "int": case "integer": case "bit": case "smallint": newType = "int"; break; case "long": case "bitint": newType = "long"; break; case "date": case "datetime": case "datetime2": case "datetimeoffset": newType = "DateTime"; break; case "decimal": case "number": case "money": case "numeric": newType = "Decimal"; break; case "double": newType = "double"; break; case "float": newType = "float"; break; } return newType; } } }
下面就是生成代码的具体步骤了:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.IO;using EntityCodeBuilder.Entity;namespace WindowsDemo { public class CreateFileHelper { /// <summary> /// 创建类文件目录和文件 /// </summary> /// <param name="tables">所有表</param> /// <param name="fileDir">文件目录</param> public static void Create(List<TableName> tables, string fileDir) { CreateDirectory(fileDir); foreach (TableName table in tables) { //实体类名称 string entityName = GenVarName(table.Name); //实体类文件名 string filePath = fileDir + entityName + ".cs"; //文件是否存在 bool exists = File.Exists(filePath); //创建文件 FileStream fs = new FileStream(filePath, exists ? FileMode.Open : FileMode.Create, FileAccess.Write); StreamWriter sw = new StreamWriter(fs); //生成代码 string code = CreateFileHelper.BuilderCode(table.Name); //写入代码到文件 sw.WriteLine(code); sw.Close(); fs.Close(); } } /// <summary> /// 创建文件目录 /// </summary> /// <param name="targetDir"></param> private static void CreateDirectory(string targetDir) { DirectoryInfo dir = new DirectoryInfo(targetDir); if (!dir.Exists) dir.Create(); } /// <summary> /// 根据表名,生成代码 /// </summary> /// <param name="tableName">表名</param> /// <returns></returns> public static string BuilderCode(string tableName) { string entityName = GenVarName(tableName); StringBuilder sb = new StringBuilder(); sb.Append("using System;").Append("\n"); sb.Append("using System.Collections.Generic; ").Append("\n"); sb.Append("using System.Linq; ").Append("\n"); sb.Append("using System.Text; ").Append("\n"); sb.Append("using System.Text; ").Append("\n"); sb.Append("namespace Easy4net.Entity ").Append("\n"); sb.Append("{ ").Append("\n"); sb.Append("\t [Table(Name = \"").Append(tableName).Append("\")] ").Append("\n"); sb.Append("\t public class ").Append(entityName).Append("\n"); sb.Append("\t { ").Append("\n"); List<TableColumn> columns = TableHelper.GetColumnField(tableName); foreach (TableColumn column in columns) { string type = TypeHelper.GetType(column.Type); if (column.IsPrimaryKey == "√") { //[Id(Name = "UserID", Strategy = GenerationType.INDENTITY)] string strategy = "GUID"; if (column.IsIdentity == "√") { strategy = "INDENTITY"; } sb.Append("\t\t").Append("[Id(Name = \"").Append(column.Name).Append("\", Strategy = GenerationType.").Append(strategy).Append(")]").Append("\n"); } else { sb.Append("\t\t").Append("[Column(Name = \"").Append(column.Name).Append("\")]").Append("\n"); } string fieldName = GenVarName(column.Name); sb.Append("\t\t").Append("public ").Append(type).Append(" ").Append(fieldName).Append("{ get; set; } \n\n"); } sb.Append("\t } ").Append("\n"); sb.Append("} ").Append("\n"); return sb.ToString(); } /// <summary> /// 将数据库中变量名改为驼峰命名 /// 如 user_name 改为 UserName /// </summary> /// <param name="name">变量名</param> /// <returns></returns> public static string GenVarName(string name) { string first = name.Substring(0, 1); name = name.Substring(1, name.Length - 1); name = first.ToUpper() + name; int index = name.IndexOf("_"); while (index != -1) { if (name.Length >= index + 2) { first = name.Substring(index + 1, 1); string start = name.Substring(0, index); string end = name.Substring(index + 2, name.Length - index - 2); name = start + first.ToUpper() + end; index = name.IndexOf("_"); } } name = name.Replace("_", ""); return name; } } }
金笛短信中间件Web版本和研发信息发布
你报 http://www.nibao.net/
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。