T4 (Text Template Transformation Toolkit) 是一个基于模板的代码生成器。使用T4你可以通过写一些ASP.NET-like模板,来生成C#, T-SQL, XML等代码。

下载示例代码

一 “Hello World ”代码生成器

1 创建一个C# Console工程,添加一个名为“HelloWorld.tt”的文本文件,将<#@ output extension=".cs" #>设为".cs"便会生成cs文件。

2 向HelloWorld.tt中添加以下内容

<#@ template language="C#" #>

// <autogenerated>

// This code was generated by a tool. Any changes made manually will be lost

// the next time this code is regenerated.

// </autogenerated>

usingSystem;

public class<#= this.ClassName #>

{

public static voidHelloPot()

{

Console.WriteLine("Hello World");

}

}

上面的模板将生成一个名为“HelloWorld”的类,当你保存HelloWorld.tt时,Visual Studio将为你生成以下代码:

// <autogenerated>

// This code was generated by a tool. Any changes made manually will be lost

// the next time this code is regenerated.

// </autogenerated>

using System;
public class HelloWorld
{
public static void HelloPot()
{
Console.WriteLine("Hello World");
}
}

3 添加另一个文本文件HelloWorld1.tt.,加入以下内容:

<#

this.ClassName = "HelloWorld1";

#>

<#@ include file="HelloT4.tt" #>

通过修改ClassName的值可以更改类名,以上模板将生成一个名为HelloWorld1类。

// <autogenerated>

// This code was generated by a tool. Any changes made manually will be lost

// the next time this code is regenerated.

// </autogenerated>

using System;   

public class HelloWorld1
{
public static void HelloPot()
{
Console.WriteLine("Hello World");
} }

二 数据库自动生成实体类

这个实例会创建一个模板为数据库中的每一张表,自动创建相应的实体类。

1 首先我们需要添加一些程序集引用,命名空间。

<#@ template language="C#" debug="True" hostspecific="True" #>

<#@ output extension=".cs" #>

<#@ assembly name="System.Data" #>

<#@ assembly name="System.xml" #>

<#@ import namespace="System.Collections.Generic" #>

<#@ import namespace="System.Data.SqlClient" #>

<#@ import namespace="System.Data" #>

2 获取数据库表结构.

<#

stringconnectionString = "data source=.""SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=MIAPortal;";

SqlConnection conn = newSqlConnection(connectionString);

conn.Open();

System.Data.DataTable schema = conn.GetSchema("TABLES");

stringselectQuery = "select * from @tableName";

SqlCommand command = newSqlCommand(selectQuery,conn);

SqlDataAdapter ad = newSqlDataAdapter(command);

System.Data.DataSet ds = newDataSet();

我们通过GetSchema("TABLES")获取了数据库中所有表的表名,接着通过表名,获取相应表的表结构。

3 生成代码如下

<#@ template language="C#" debug="True" hostspecific="True" #>

<#@ output extension=".cs" #>

<#@ assembly name="System.Data" #>

<#@ assembly name="System.xml" #>

<#@ import namespace="System.Collections.Generic" #>

<#@ import namespace="System.Data.SqlClient" #>

<#@ import namespace="System.Data" #>

 using System;

namespace MyProject.Entities

{     

      <#

           string connectionString = "data source=.""SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=MIAPortal;";

           SqlConnection conn = new SqlConnection(connectionString);

           conn.Open();

           System.Data.DataTable schema = conn.GetSchema("TABLES");

           string selectQuery = "select * from @tableName";

           SqlCommand command = new SqlCommand(selectQuery,conn);

           SqlDataAdapter ad = new SqlDataAdapter(command);

           System.Data.DataSet ds = new DataSet();        

           foreach(System.Data.DataRow row in schema.Rows)

           {  #>  

           public class <#= row["TABLE_NAME"].ToString().Trim('s') #>                   

           {    <#                     

                   ds.Tables.Clear();

                  command.CommandText = selectQuery.Replace("@tableName",row["TABLE_NAME"].ToString());

                  ad.FillSchema(ds, SchemaType.Mapped, row["TABLE_NAME"].ToString());         

                  foreach (DataColumn dc in ds.Tables[].Columns)

                  {    #>                    

                  private <#= dc.DataType.Name #> _<#= dc.ColumnName.Replace(dc.ColumnName[].ToString(), dc.ColumnName[].ToString().ToLower())      #>;                      

                  public <#= dc.DataType.Name #> <#= dc.ColumnName #>

                  {

                     get { return _<#= dc.ColumnName.Replace(dc.ColumnName[].ToString(), dc.ColumnName[].ToString().ToLower()) #>; }

                     set { _<#= dc.ColumnName.Replace(dc.ColumnName[].ToString(), dc.ColumnName[].ToString().ToLower()) #> = value; }

                  }                                                

              <# }  #>         

           }                  

           <# 

           } #>                

}

使用T4为数据库自动生成实体类的更多相关文章

  1. Asp.Net Core如何根据数据库自动生成实体类

    通过引用Nuget包添加实体类 运行 Install-Package Microsoft.EntityFrameworkCore.SqlServer 运行 Install-Package Micros ...

  2. T4模板根据DB生成实体类

    1.前言 为什么会有这篇文章了,最近看到了一些框架,里面要写的代码太多了,故此就想偷懒,要是能写出一个T4模板,在数据库添加表后,根据模板就可以自动生成了类文件了,这样多好,心动不如行动.记得使用T4 ...

  3. MyEclipse数据库反向生成实体类

    MyEclipse数据库反向生成实体类 “计应134(实验班) 凌豪” 当我们在开发项目涉及到的表太多时,一个一个的写JAVA实体类很是费事.然而强大的MyEclipse为我们提供简便的方法:数据库反 ...

  4. J2EE进阶(十五)MyEclipse反向工程实现从数据库反向生成实体类之Hibernate方式

    J2EE进阶(十五)MyEclipse反向工程实现从数据库反向生成实体类之Hibernate方式   反向工程又称逆向工程.   开发项目涉及到的表太多,一个一个的写JAVA实体类很是费事.MyEcl ...

  5. Mybatis自动生成实体类

    Maven自动生成实体类需要的jar包 一.pom.xml中 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns ...

  6. 【.NetCore学习】ASP.NET Core EF Core2.0 DB First现有数据库自动生成实体Context

    主要参考微软官方文档 https://docs.microsoft.com/en-us/ef/core/get-started/aspnetcore/existing-db Microsoft .NE ...

  7. Springboot mybatis generate 自动生成实体类和Mapper

    https://github.com/JasmineQian/SpringDemo_2019/tree/master/mybatis Springboot让java开发变得方便,Springboot中 ...

  8. Mybatis自动生成实体类、dao接口和mapping映射文件

    由于Mybatis是一种半自动的ORM框架,它的工作主要是配置mapping映射文件,为了减少手动书写映射文件,可以利用mybatis生成器,自动生成实体类.dao接口以及它的映射文件,然后直接拷贝到 ...

  9. .net core 中简单封装Dapper.Extensions 并使用sqlsuger自动生成实体类

    引言 由公司需要使用dapper  同时支持多数据库 又需要支持实体类 又需要支持sql 还需要支持事务 所以采用了 dapper + dapperExtensions  并配套 生成实体类小工具的方 ...

随机推荐

  1. 实用的树形菜单控件tree

     jQuery plugin: Treeview  这个插件能够把无序列表转换成可展开与收缩的Tree. jQuery plugin: Treeview  jQuery  jstree  jsTree ...

  2. CMSIS-DAP调试器

    http://www.keil.com/support/man/docs/dapdebug/dapdebug_introduction.htm CMSIS-DAP is the interface f ...

  3. SCCM2012分发脚本

    1.分发批处理脚本 命令行:script.bat 2.分发PowerShell脚本 命令行:PowerShell.exe -executionpolicy unrestricted -file .\s ...

  4. Pre-compile (pre-JIT) your assembly on the fly, or trigger JIT compilation ahead-of-time (转)

    Introduction All .NET developers know that one of the best features of the CLR is JIT-compilation: J ...

  5. C++经典面试题

    1.int a=5,则 ++(a++)的值是() A.5      B.   6          C.7       D.逻辑错误 a++返回的是一个暂时变量,这里是右值,不能再前面++了 2.以下 ...

  6. 一个获取文件绝对路径的sh

    脚本里有个获取文件绝对路径的需求,linux里有个很方便的realpath命令,但是mac下没有,甚至readlink -f也跟linux下的表现不同,所以……直接用pwd算了 #!/bin/bash ...

  7. VS2013 安装phonegap

    https://www.microsoft.com/en-us/download/details.aspx?id=40783

  8. WinForm特效:拦截窗体上各个部位的点击

    windows窗体的标题栏无法直接通过一些默认的事件来控制,需要了解和WM_NCHITTEST相关的windows消息. 以下示例演示了最简单的效果片断: 他会把客户区和标题栏的效果互换,比如无法按住 ...

  9. [Angular 2] Style Angular 2 Components

    Each Angular 2 Component can have its own styles which will remained contained inside the component. ...

  10. VC6.0常见编译错误提示

    原文:http://c.biancheng.net/cpp/html/746.html 1) error C2001: newline in constant 编号:C2001 直译:在常量中出现了换 ...