建立文本模板TextTemplate1.tt和DbHelper.ttinclude

TextTemplate1.tt  代码:

<#@ assembly name="System.Core.dll" #>
<#@ assembly name="System.Data.dll" #>
<#@ assembly name="System.Data.DataSetExtensions.dll" #>
<#@ assembly name="System.Xml.dll" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Xml" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Data" #>
<#@ import namespace="System.Data.SqlClient" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.IO" #><#@ include file="$(ProjectDir)DbHelper.ttinclude"  #>using System;
namespace T4ConsoleApplication.Entities
{    public class <#=config.TableName#>{<# foreach(DbColumn column in DbHelper.GetDbColumns(config.ConnectionString, config.DbDatabase, config.TableName)){#>public <#= column.CSharpType#><# if(column.CommonType.IsValueType && column.IsNullable){#>?<#}#> <#=column.ColumnName#> { get; set; }<#}#> }
}<#+public class config{//修改要生成的数据库表public static readonly string ConnectionString="Data Source=.;User ID=MyUserID; password=MyPwd;";public static readonly string DbDatabase="MyDataBase";public static readonly string TableName="MyTable";}
#>

DbHelper.ttinclude 代码:

<#+public class DbHelper{#region GetDbTablespublic static List<DbTable> GetDbTables(string connectionString, string database, string tables = null){if (!string.IsNullOrEmpty(tables)){tables = string.Format(" and obj.name in ('{0}')", tables.Replace(",", "','"));}#region SQLstring sql = string.Format(@"SELECTobj.name tablename,schem.name schemname,idx.rows,CAST(CASE WHEN (SELECT COUNT(1) FROM sys.indexes WHERE object_id= obj.OBJECT_ID AND is_primary_key=1) >=1 THEN 1ELSE 0END AS BIT) HasPrimaryKey                                         from {0}.sys.objects obj inner join {0}.dbo.sysindexes idx on obj.object_id=idx.id and idx.indid<=1INNER JOIN {0}.sys.schemas schem ON obj.schema_id=schem.schema_idwhere type='U' {1}order by obj.name", database, tables);#endregionDataTable dt = GetDataTable(connectionString, sql);return dt.Rows.Cast<DataRow>().Select(row => new DbTable{TableName = row.Field<string>("tablename"),SchemaName = row.Field<string>("schemname"),Rows = row.Field<int>("rows"),HasPrimaryKey = row.Field<bool>("HasPrimaryKey")}).ToList();}#endregion#region GetDbColumnspublic static List<DbColumn> GetDbColumns(string connectionString, string database, string tableName, string schema = "dbo"){#region SQLstring sql = string.Format(@"WITH indexCTE AS(SELECT ic.column_id,ic.index_column_id,ic.object_id    FROM {0}.sys.indexes idxINNER JOIN {0}.sys.index_columns ic ON idx.index_id = ic.index_id AND idx.object_id = ic.object_idWHERE  idx.object_id =OBJECT_ID(@tableName) AND idx.is_primary_key=1)selectcolm.column_id ColumnID,CAST(CASE WHEN indexCTE.column_id IS NULL THEN 0 ELSE 1 END AS BIT) IsPrimaryKey,colm.name ColumnName,systype.name ColumnType,colm.is_identity IsIdentity,colm.is_nullable IsNullable,cast(colm.max_length as int) ByteLength,(case when systype.name='nvarchar' and colm.max_length>0 then colm.max_length/2 when systype.name='nchar' and colm.max_length>0 then colm.max_length/2when systype.name='ntext' and colm.max_length>0 then colm.max_length/2 else colm.max_lengthend) CharLength,cast(colm.precision as int) Precision,cast(colm.scale as int) Scale,prop.value Remarkfrom {0}.sys.columns colminner join {0}.sys.types systype on colm.system_type_id=systype.system_type_id and colm.user_type_id=systype.user_type_idleft join {0}.sys.extended_properties prop on colm.object_id=prop.major_id and colm.column_id=prop.minor_idLEFT JOIN indexCTE ON colm.column_id=indexCTE.column_id AND colm.object_id=indexCTE.object_id                                        where colm.object_id=OBJECT_ID(@tableName)order by colm.column_id", database);#endregionSqlParameter param = new SqlParameter("@tableName", SqlDbType.NVarChar, 100) { Value = string.Format("{0}.{1}.{2}", database, schema, tableName) };DataTable dt = GetDataTable(connectionString, sql, param);            return dt.Rows.Cast<DataRow>().Select(row => new DbColumn(){ColumnID = row.Field<int>("ColumnID"),IsPrimaryKey = row.Field<bool>("IsPrimaryKey"),ColumnName = row.Field<string>("ColumnName"),ColumnType = row.Field<string>("ColumnType"),IsIdentity = row.Field<bool>("IsIdentity"),IsNullable = row.Field<bool>("IsNullable"),ByteLength = row.Field<int>("ByteLength"),CharLength = row.Field<int>("CharLength"),Scale = row.Field<int>("Scale"),Remark = row["Remark"].ToString()}).ToList();}#endregion     #region GetDataTablepublic static DataTable GetDataTable(string connectionString, string commandText, params SqlParameter[] parms){using (SqlConnection connection = new SqlConnection(connectionString)){SqlCommand command = connection.CreateCommand();command.CommandText = commandText;command.Parameters.AddRange(parms);SqlDataAdapter adapter = new SqlDataAdapter(command);                DataTable dt = new DataTable();adapter.Fill(dt);return dt;}}#endregion}#region DbTable/// <summary>/// 表结构/// </summary>public sealed class DbTable{/// <summary>/// 表名称/// </summary>public string TableName { get; set; }/// <summary>/// 表的架构/// </summary>public string SchemaName { get; set; }/// <summary>/// 表的记录数/// </summary>public int Rows { get; set; }/// <summary>/// 是否含有主键/// </summary>public bool HasPrimaryKey { get; set; }}#endregion#region DbColumn/// <summary>/// 表字段结构/// </summary>public sealed class DbColumn{/// <summary>/// 字段ID/// </summary>public int ColumnID { get; set; }/// <summary>/// 是否主键/// </summary>public bool IsPrimaryKey { get; set; }/// <summary>/// 字段名称/// </summary>public string ColumnName { get; set; }/// <summary>/// 字段类型/// </summary>public string ColumnType { get; set; }/// <summary>/// 数据库类型对应的C#类型/// </summary>public string CSharpType{get{return SqlServerDbTypeMap.MapCsharpType(ColumnType);}}/// <summary>/// /// </summary>public Type CommonType{get{return SqlServerDbTypeMap.MapCommonType(ColumnType);}}/// <summary>/// 字节长度/// </summary>public int ByteLength { get; set; }/// <summary>/// 字符长度/// </summary>public int CharLength { get; set; }/// <summary>/// 小数位/// </summary>public int Scale { get; set; }/// <summary>/// 是否自增列/// </summary>public bool IsIdentity { get; set; }/// <summary>/// 是否允许空/// </summary>public bool IsNullable { get; set; }/// <summary>/// 描述/// </summary>public string Remark { get; set; }}#endregion#region SqlServerDbTypeMappublic class SqlServerDbTypeMap{public static string MapCsharpType(string dbtype){if (string.IsNullOrEmpty(dbtype)) return dbtype;dbtype = dbtype.ToLower();string csharpType = "object";switch (dbtype){case "bigint": csharpType = "long"; break;case "binary": csharpType = "byte[]"; break;case "bit": csharpType = "bool"; break;case "char": csharpType = "string"; break;case "date": csharpType = "DateTime"; break;case "datetime": csharpType = "DateTime"; break;case "datetime2": csharpType = "DateTime"; break;case "datetimeoffset": csharpType = "DateTimeOffset"; break;case "decimal": csharpType = "decimal"; break;case "float": csharpType = "double"; break;case "image": csharpType = "byte[]"; break;case "int": csharpType = "int"; break;case "money": csharpType = "decimal"; break;case "nchar": csharpType = "string"; break;case "ntext": csharpType = "string"; break;case "numeric": csharpType = "decimal"; break;case "nvarchar": csharpType = "string"; break;case "real": csharpType = "Single"; break;case "smalldatetime": csharpType = "DateTime"; break;case "smallint": csharpType = "short"; break;case "smallmoney": csharpType = "decimal"; break;case "sql_variant": csharpType = "object"; break;case "sysname": csharpType = "object"; break;case "text": csharpType = "string"; break;case "time": csharpType = "TimeSpan"; break;case "timestamp": csharpType = "byte[]"; break;case "tinyint": csharpType = "byte"; break;case "uniqueidentifier": csharpType = "Guid"; break;case "varbinary": csharpType = "byte[]"; break;case "varchar": csharpType = "string"; break;case "xml": csharpType = "string"; break;default: csharpType = "object"; break;}return csharpType;}public static Type MapCommonType(string dbtype){if (string.IsNullOrEmpty(dbtype)) return Type.Missing.GetType();dbtype = dbtype.ToLower();Type commonType = typeof(object);switch (dbtype){case "bigint": commonType = typeof(long); break;case "binary": commonType = typeof(byte[]); break;case "bit": commonType = typeof(bool); break;case "char": commonType = typeof(string); break;case "date": commonType = typeof(DateTime); break;case "datetime": commonType = typeof(DateTime); break;case "datetime2": commonType = typeof(DateTime); break;case "datetimeoffset": commonType = typeof(DateTimeOffset); break;case "decimal": commonType = typeof(decimal); break;case "float": commonType = typeof(double); break;case "image": commonType = typeof(byte[]); break;case "int": commonType = typeof(int); break;case "money": commonType = typeof(decimal); break;case "nchar": commonType = typeof(string); break;case "ntext": commonType = typeof(string); break;case "numeric": commonType = typeof(decimal); break;case "nvarchar": commonType = typeof(string); break;case "real": commonType = typeof(Single); break;case "smalldatetime": commonType = typeof(DateTime); break;case "smallint": commonType = typeof(short); break;case "smallmoney": commonType = typeof(decimal); break;case "sql_variant": commonType = typeof(object); break;case "sysname": commonType = typeof(object); break;case "text": commonType = typeof(string); break;case "time": commonType = typeof(TimeSpan); break;case "timestamp": commonType = typeof(byte[]); break;case "tinyint": commonType = typeof(byte); break;case "uniqueidentifier": commonType = typeof(Guid); break;case "varbinary": commonType = typeof(byte[]); break;case "varchar": commonType = typeof(string); break;case "xml": commonType = typeof(string); break;default: commonType = typeof(object); break;}return commonType;}}#endregion#>

直接保存即可生成指定数据库表实体生成的实体:

转载于:https://www.cnblogs.com/J5288/p/8295250.html

T4 生成指定DB表实体相关推荐

  1. Java实现自动生成Mysql数据库表实体类

    2019独角兽企业重金招聘Python工程师标准>>> 一个工具类就可以实现啦,直接看代码及注释,很方便理解,从一位博主那里拿到加上自己优化一部分的 注:侵删(忘了原博主信息) My ...

  2. R语言使用reshape2包的melt函数将dataframe从宽表到长表(Wide- to long-format)、指定行标识符变量、并自定义生成的长表的标识符列的名称

    R语言使用reshape2包的melt函数将dataframe从宽表到长表(Wide- to long-format).指定行标识符变量.并自定义生成的长表的标识符列的名称 目录

  3. Intellij IDEA 通过数据库表逆向生成带注释的实体类文件超级详细步骤,附详细解决方案

    Intellij IDEA 通过数据库表逆向生成带注释的实体类文件超级详细步骤,附详细解决方案 参考文章: (1)Intellij IDEA 通过数据库表逆向生成带注释的实体类文件超级详细步骤,附详细 ...

  4. jpa 定义中间表实体_JPA系列之-带你快速掌握JPA

    课程目录: 课程目标:理解JPA规范,JPA提供商,JPA的优势,JPA的具体开发应用.JPA是SUN公司定义的持久化API,相当于JDBC的角色,以统一的接口访问数据库,通过本课程的学习,让大家快速 ...

  5. GreenDao 工具类 --- 使用 Json 快速生成 Bean、表及其结构,炒鸡快!

    作者:林冠宏 / 指尖下的幽灵 掘金:https://juejin.im/user/587f0dfe128fe100570ce2d8 博客:http://www.cnblogs.com/linguan ...

  6. 给MYSQL账号充值的软件_MYSQL数据库指定数据库表给会员充值充值教程

    MYSQL数据库指定数据库表给会员充值充值教程 $db=new cls_mysql(array( 'dbhost'=>'要充值数据库IP', 'dbname'=>'要充值的数据库用户名', ...

  7. mysql 数据展示装置_实时生成数据宽表的方法和装置与流程

    本发明涉及计算机技术领域,尤其涉及一种实时生成数据宽表的方法和装置. 背景技术: 数据仓库是面向主题的.集成的.相对稳定的.随时间不短变化得数据集合,用以支持经营管理中的决策制定.数据仓库中的数据面向 ...

  8. python读取excel指定列-Python读取excel指定列生成指定sql脚本的方法

    需求 最近公司干活,收到一个需求,说是让手动将数据库查出来的信息复制粘贴到excel中,在用excel中写好的公式将指定的两列数据用update这样的语句替换掉. 例如: 有个A库,其中有两个A.01 ...

  9. Oracle-Oracle SQL Report (awrsqrpt.sql/awrsqrpi.sql)生成指定SQL的统计报表

    概述 我们知道,Oracle提供的脚本均位于下列目录下 $ORACLE_HOME/rdbms/admin 其中, awrsqrpt.sql用来分析某条指定的SQL语句,通过awrsqrpt.sql脚本 ...

  10. 窗口分析函数_7_生成指定的分组序号

    生成指定的分组序号 需求描述 需求:将EMP表里的部门编号为20的SAL字段按照由高到低排序后分为4组. 解决方法:通过ntile OVER()来完成. 注: 数据库数据集SQL脚本详见如下链接地址 ...

最新文章

  1. Hadoop 2.0 Yarn代码:心跳驱动服务分析
  2. 面向对象的C语言开发框架:Nesty
  3. thinkphp模板中使用方法
  4. java定时任务框架elasticjob详解
  5. css中position的两种定位(absolute、relative)
  6. 腾讯-视频打标签算法探讨
  7. android inset 标签,android – 有几个WindowInsets?
  8. cmake 常用变量和常用环境变量
  9. 王者荣耀总决赛因天气原因延期 玩家获得皮肤碎片等补偿
  10. kafka sasl java_kafka 添加SASL鉴权
  11. linux命令行界面如何安装图形化界面
  12. springboot+1、图片上传到本地路径信息保存在数据库2、根据id删除本地图片
  13. 人工神经网络matlab啊6,基于MATLAB6.x的BP人工神经网络的土壤环境质量评价方法研究...
  14. 石家庄网站建设公司详解企业网站建设方案策划
  15. android 开发短信接收器
  16. 【shaderforge学习笔记】 Rotator节点
  17. 封装微信小程序api请求地址
  18. 《C语言入门》简单回文序列问题求解
  19. Halcon消除畸变
  20. electron打包应用再win7无法启动解决方案

热门文章

  1. 一分钟看懂Docker的网络模式和跨主机通信
  2. iOS开发中的小Tips
  3. JSP中使用的模式——JSP+Servlet+JavaBean
  4. 对于NAS,IP SAN以及iSCSCI SAN存储的一些认识和理解
  5. JQuery淡入淡出 banner切换特效
  6. IIS7 上部署MVC3,执行错误:Could not load type 'System.ServiceModel.Activation.HttpModule'
  7. linux 中select()函数的使用
  8. CSS让同一行文字和输入框对齐
  9. maven 基本常识以及命令
  10. poj-3176 Cow Bowling poj-1163 The Triangle hihocoder #1037 : 数字三角形 (基础dp)