自己目前在搭建一个.NET Core的框架,本来是打算使用前端做代码生成器直接生成到文件的,快做好了。感觉好像使用T4更方便一些,所以也就有了这篇文章~ 

我还是有个问题没解决,就是我想生成每个类(接口)单独的文件~,如果有老师知道指点下啊~

在网上找了一篇相关文章 本文也是基于这个做了一下自己的修改。

首先公共程序集创建一个DbHelper.ttinclude

主要就是链接数据库,搜索数据库表及表中字段的信息。

你可以得到这样的结果:瞬间明了了,然后就  爱的魔力转圈圈~ 循环就好了!

代码是这样的:

<#+public class config{public static readonly string ConnectionString="Data Source=(local);Integrated Security=true;Initial Catalog=LJDAPP;";public static readonly string DbDatabase="LJDAPP"; }public class DbHelper{ public static List<DbTable> GetDbTables(string connectionString, string database){ string sql = string.Format(@"SELECTobj.name tablename,schem.name schemname,ISNULL(g.value,'') [description],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_idleft join {0}.sys.extended_properties g ON (obj.object_id = g.major_id AND g.minor_id = 0 AND g.name= 'MS_Description')where type='U' order by obj.name", database); DataTable dt = GetDataTable(connectionString, sql);return dt.Rows.Cast<DataRow>().Select(row => new DbTable{TableName = row.Field<string>("tablename"),SchemaName = row.Field<string>("schemname"),Description=row.Field<string>("description"),Rows = row.Field<int>("rows"),HasPrimaryKey = row.Field<bool>("HasPrimaryKey")}).ToList();}public static List<DbColumn> GetDbColumns(string connectionString, string database, string tableName, string schema = "dbo"){ string 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);SqlParameter 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();}public 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;}}}/// <summary>/// 表结构/// </summary>public sealed class DbTable{/// <summary>/// 表名称/// </summary>public string TableName { get; set; }/// <summary>/// 表的架构/// </summary>public string SchemaName { get; set; }/// <summary>/// 表的说明/// </summary>public string Description { get; set; }/// <summary>/// 表的记录数/// </summary>public int Rows { get; set; }/// <summary>/// 是否含有主键/// </summary>public bool HasPrimaryKey { get; set; }}/// <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; }}public 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;}}#>

View Code

这个其实也是可以一起放到模板里的,不过因为好几个地方都需要用到,为了修改方便,还是单独拿出来比较好。

使用的时候会用到:

<#@ include file="$(ProjectDir)../LJD.App.Util/T4/DbHelper.ttinclude"  #>

显而易见,我放到了 LJD.App.Util类库下T4文件夹

这里说下T4 程序集指令  还有一篇文章:T4模版引擎之基础入门 是这样说的

<#@ assembly name="[assembly strong name|assembly file name]" #>

1、程序集指令相当于VS里面我们添加程序集引用的功能,该指令只有一个参数name,用以指定程序集名称,如果程序集已经在GAC里面注册,那么只需要写上程序集名称即可,如<#@ assembly name="System.Data.dll" #>,否则需要指定程序集的物理路径。

2、T4模版的程序集引用是完全独立的,也就是说我们在项目中引用了一些程序集,然后项目中添加了一个T4模版,T4模版所需要的所有程序集引用必须明确的在模版中使用程序集执行引用才可以。

3、T4模版自动加载以下程序集Microsoft.VisualStudio.TextTemplating.1*.dll、System.dll、WindowsBase.dll,如果用到了其它的程序集需要显示的使用程序集添加引用才可以

4、可以使用 $(variableName) 语法引用 Visual Studio 或 MSBuild 变量(如 $(SolutionDir)),以及使用 %VariableName% 来引用环境变量。介绍几个常用的$(variableName) 变量:

    $(SolutionDir):当前项目所在解决方案目录

    $(ProjectDir):当前项目所在目录

    $(TargetPath):当前项目编译输出文件绝对路径

    $(TargetDir):当前项目编译输出目录,即web项目的Bin目录,控制台、类库项目bin目录下的debug或release目录(取决于当前的编译模式)

    举个例子:比如我们在D盘根目录建立了一个控制台项目TestConsole,解决方案目录为D:\LzrabbitRabbit,项目目录为
    D:\LzrabbitRabbit\TestConsole,那么此时在Debug编译模式下
    $(SolutionDir)的值为D:\LzrabbitRabbit
    $(ProjectDir)的值为D:\LzrabbitRabbit\TestConsole
    $(TargetPath)值为D:\LzrabbitRabbit\TestConsole\bin\Debug\TestConsole.exe
    $(TargetDir)值为D:\LzrabbitRabbit\TestConsole\bin\Debug\

好了,准备工作都做完了,要创建T4模板了,这个还要图吗?

然后贴上这段代码,在foreach中发挥你的想想吧!对了,要注意命名空间和using哈~

<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Data" #>
<#@ assembly name="System.Data.DataSetExtensions" #>
<#@ assembly name="System.Xml" #>
<#@ 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)../LJD.App.Util/T4/DbHelper.ttinclude"  #>
//------------------------------------------------------------------------------
// <auto-generated>
//     此代码由T4模板自动生成
//     生成时间 <#=        DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")#> by Jelly
//     对此文件的更改可能会导致不正确的行为,并且如果重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
using LJD.App.Model.DbModels;namespace LJD.App.Repository.IRepository
{<#    foreach(DbTable table in DbHelper.GetDbTables(config.ConnectionString, config.DbDatabase)){#>
<#        if(table.TableName!="Base") {#>/// <summary>/// <#=table.Description#>/// </summary>        public partial interface I<#=table.TableName#>Repository : IBaseRepository<<#=table.TableName#>>{}
<#} #><#     }#>
}  

转载于:https://www.cnblogs.com/jellydong/p/10838075.html

T4模板使用记录,生成Model、Service、Repository相关推荐

  1. php lmpl,tjx-cold: 用于根据配置模板,快速生成controller,service,serviceimpl 代码

    用于根据配置模板,快速生成controller,service,serviceimpl 代码(交流群 623169994 ) 为什么要开发这款插件 市面上有很多基于数据库生成代码的工具,但是我自己的工 ...

  2. t4模板 mysql_.net core 用T4模板连接MySql生成实体类

    .net core 用T4模板连接MySql生成实体类标题 4,把MySql.Data.dll放在项目根目录,也可以自行更改. 在之前参考那个博友的文章,他的是连接SQL server的. 下面是参考 ...

  3. .NET中关于T4模板的使用

    文章目录 介绍 简单说下什么是t4模版 具体使用方式 TransformText方法 自定义T4模板引擎 两种方式的比较 总结 介绍 最近工作中需要按一定的模板模型生成指定的文件,虽然可以直接拼接字符 ...

  4. [转]MVC实用架构设计(三)——EF-Code First(3):使用T4模板生成相似代码

    本文转自:http://www.cnblogs.com/guomingfeng/p/mvc-ef-t4.html 〇.目录 一.前言 二.工具准备 三.T4代码生成预热 (一) 单文件生成:Hello ...

  5. T4模板:MVC中用T4模板快速生成代码

    T4模板快速生成代码: 以快速生Dal文件为例,下面为T4模板文件的内容 <#@ template debug="false" hostspecific="true ...

  6. 创建代码生成器可以很简单:如何通过T4模板生成代码?[上篇]

    在<基于T4的代码生成方式>中,我对T4模板的组成结构.语法,以及T4引擎的工作原理进行了大体的介绍,并且编写了一个T4模板实现了如何将一个XML转变成C#代码.为了让由此需求的读者对T4 ...

  7. [转]使用T4模板批量生成代码

    本文转自:http://www.cnblogs.com/K_tommy/archive/2013/04/06/T4.html 前言 之前在 "使用T4模板生成代码 - 初探" 文章 ...

  8. FluentData-新型轻量级ORM 利用T4模板 批量生成多文件 实体和业务逻辑 代码

    FluentData,它是一个轻量级框架,关注性能和易用性. 下载地址:FlunenData.Model 利用T4模板,[MultipleOutputHelper.ttinclude]批量生成多文件 ...

  9. 创建代码生成器可以很简单:如何通过T4模板生成代码?[下篇]

    在<上篇>中我们通过T4模板为我们指定的数据表成功生成了我们需要的用于添加.修改和删除操作的存储过程.但是这是一种基于单个文件的解决方案,即我们必须为每一个生成的存储过程建立一个模板.如果 ...

最新文章

  1. HashSet中的add()方法( 一 )(详尽版)
  2. 联想拯救者y空间兑换代码_十代酷睿全面升级 拯救者Y7000P 2020产品解读
  3. SOJ 2800_三角形
  4. Perl语言编程学习笔记2
  5. MySql 优化的 30 条建议
  6. python 取整_马克的Python学习笔记#数字,日期和时间
  7. 基于微博数据对突发性环境污染事件公众感知变迁研究
  8. Ubuntu的默认root密码是多少,修改root密码
  9. js return 闭包为null_那么如何让你的 JS 写得更漂亮?
  10. 数据库新技术:分布式数据库的体系结构,特点与查询优化(思维导图版总结)
  11. html邮箱留言板代码,求HTML留言板代码或模板?
  12. 网页源代码怎么屏蔽?
  13. 新 Nsight Graph、Nsight Aftermath 版本中的性能提升和增强功能
  14. Enviropro EP100D-08管式土壤水分探针
  15. 关于LIS系统与HIS系统的接口方案
  16. 网络适配器出现黄色感叹号!,错误代码56
  17. cgb2106-day12
  18. 【实现】Java实现的文件批量改名
  19. 【数据集介绍】The Idiap Research Institute REPLAY-Mobile Database
  20. fprintf()函数的使用

热门文章

  1. 让你真正体验一次主板超频的步骤以及成功的快乐
  2. Django的是如何工作的
  3. ACM模板--邻接表 无向图 Prim Kruskal Dijkstra
  4. 后缀数组--处理字符串的利器
  5. C语言中sizeof与strlen的区别总结!
  6. 常考数据结构与算法:查找第K大元素算法
  7. springboot:thymeleaf
  8. java: http请求和响应
  9. java程序初始化顺序
  10. 前端一HTML:二十三行高的介绍,行高的单位