1.用vs新建tt文件.

2.tt文件保存就自动运行

3.tt文件代码如下,设置生成cs文件的命名空间和生成地址

<#@ template language="C#" hostspecific="true" debug="True" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Data" #>
<#@ assembly name="System.Xml" #>
<#@ assembly name="Microsoft.SqlServer.Smo" #>
<#@ assembly name="Microsoft.SqlServer.ConnectionInfo" #>
<#@ assembly name="Microsoft.SqlServer.Management.Sdk.Sfc" #>
<#@ import namespace="System" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="Microsoft.SqlServer.Management.Smo" #> <# //**********************************************************************************************
// This T4 generates POCOs from the specified DB and saves them to the specified folder which
// is relative to the template's location. One file per table/POCO.
//**********************************************************************************************
//****************************
// DEFINE YOUR VARIABLES HERE
//****************************
// The SQL server name or IP
string sqlServer = "192.168.1.1";
// The SQL username
string sqlLogin = "sa";
// The SQL password
string sqlPassword = "password";
// The SQL database to generate the POCOs for
string sqlDatabase = "databasename";
// The namespace to apply to the generated classes
string classNamespace = "RichPlugin.FYEB.Entity";
// The destination folder for the generated classes, relative to this file's location.
string destinationFolder = @"G:\\HisApp\\classT4";
// Loop over each table and create a class file!
Server server = new Server(sqlServer);
server.ConnectionContext.LoginSecure = false;
server.ConnectionContext.Login = sqlLogin;
server.ConnectionContext.Password = sqlPassword;
server.ConnectionContext.Connect(); foreach (Table table in server.Databases[sqlDatabase].Tables)
{
// Skip sys tables
string[] tables = new[] { "table1", "table2" , "table3" , "table4" };
if(!tables.Contains(table.Name))
{
continue;
} #>
using System;
namespace <#= classNamespace #>
{
/// <summary>
/// Represents a <#= table.Name #>.
/// NOTE: This class is generated from a T4 template - you should not modify it manually.
/// </summary>
public class <#= table.Name #>
{
<#
// Keep count so we don't whitespace the last property/column
int columnCount = table.Columns.Count;
int i = 0;
// Iterate all columns
foreach (Column col in table.Columns)
{
i++;
string propertyType = GetNetDataType(col.DataType.Name);
// If we can't map it, skip it
if (string.IsNullOrWhiteSpace(propertyType))
{
// Skip
continue;
}
// Handle nullable columns by making the type nullable
if (col.Nullable && propertyType != "string")
{
propertyType += "?";
}
#>
public <#= propertyType #> <#= col.Name #> { get; set; }
<#
// Do we insert the space?
if (i != columnCount)
{
#>
<#
}
#>
<#
}
#>
}
}
<#
// Write new POCO class to its own file
SaveOutput(table.Name + ".cs", destinationFolder);
}
#>
<#+
public static string GetNetDataType(string sqlDataTypeName)
{
switch (sqlDataTypeName.ToLower())
{
case "bigint":
return "Int64";
case "binary":
case "image":
case "varbinary":
return "byte[]";
case "bit":
return "bool";
case "char":
return "char";
case "datetime":
case "smalldatetime":
return "DateTime";
case "decimal":
case "money":
case "numeric":
return "decimal";
case "float":
return "double";
case "int":
return "int";
case "nchar":
case "nvarchar":
case "text":
case "varchar":
case "xml":
return "string";
case "real":
return "single";
case "smallint":
return "Int16";
case "tinyint":
return "byte";
case "uniqueidentifier":
return "Guid";
default:
return null;
}
}
void SaveOutput(string outputFileName, string destinationFolder)
{
// Write to destination folder
string templateDirectory = Path.Combine(Path.GetDirectoryName(Host.TemplateFile), destinationFolder);
string outputFilePath = Path.Combine(templateDirectory, outputFileName);
File.Delete(outputFilePath);
File.WriteAllText(outputFilePath, this.GenerationEnvironment.ToString());
// Flush generation
this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);
}
#>

c# T4模板生成实体类(sqlserver)的更多相关文章

  1. c# 使用T4模板生成实体类(sqlserver)

    新建类库,右键添加 "文本模板" 添加完成之后生成如下后缀为 tt的文件: 双击文件:TextTemplate_Test.tt 文件打开,替换代码如下 <#@ templat ...

  2. {T4模板}C# Net MVC+SqlServer=T4模板生成实体类并操作数据(DbHelper+DBManage)

    1.ConnectionString,数据库链接 Web.config <configuration> <connectionStrings> <!-- 数据库 SQL ...

  3. C# T4 模板 数据库实体类生成模板(带注释,娱乐用)

     说明:..,有些工具生成实体类没注释,不能和SqlServer的MS_Description属性一起使用,然后照着网上的资源,随便写了个生成模板,自娱自乐向,其实卵用都没有参考教程    1.htt ...

  4. 使用T4模板生成POCO类

    为什么叫T4?因为简写为4个T. T4(Text Template Transformation Toolkit)是微软官方在VisualStudio 2008中开始使用的代码生成引擎.在 Visua ...

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

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

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

    为了减少重复劳动,可以通过T4读取数据库表结构,生成实体类,用下面的实例测试了一下 1.首先创建一个项目,并添加文本模板: 2.添加 文本模板: 3.向T4文本模板文件添加代码: <#@ tem ...

  7. 使用T4模板生成MySql数据库实体类

    注:本文系作者原创,但可随意转载. 现在呆的公司使用的数据库几乎都是MySQL.编程方式DatabaseFirst.即先写数据库设计,表设计按照规范好的文档写进EXCEL里,然后用公司的宏,生成建表脚 ...

  8. 使用T4为数据库自动生成实体类

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

  9. 懒人小工具:T4生成实体类Model,Insert,Select,Delete以及导出Excel的方法

    由于最近公司在用webform开发ERP,用到大量重复机械的代码,之前写了篇文章,懒人小工具:自动生成Model,Insert,Select,Delete以及导出Excel的方法,但是有人觉得这种方法 ...

随机推荐

  1. 记一次Celery的仇

    背景:项目在公司的一台虚拟机上运行(32核+32G).其他人的项目也在这台物理机上运行..我的训练代码是单进程的,跑完一次需要大约10h(数据量大逮着一个核使劲跑..):训练是一个Celery定时任务 ...

  2. Gym - 101617D_Jumping Haybales(BFS)

    Sample Input 4 2 .### #... .#.. #.#. 3 1 .#. .#. .#. Sample Output 4 -1 题意:给一个n*n的图,每次最多能跳k个格子,只能向南( ...

  3. LeetCode54 Spiral Matrix

    题目: Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spira ...

  4. @bzoj - 4922@ [Lydsy1706月赛]Karp-de-Chant Number

    目录 @description@ @solution@ @accepted code@ @details@ @description@ 卡常数被称为计算机算法竞赛之中最神奇的一类数字,主要特点集中于令 ...

  5. HZOJ string

    正解炸了…… 考试的时候想到了正解,非常高兴的打出来了线段树,又调了好长时间,对拍了一下发现除了非常大的点跑的有点慢外其他还行.因为复杂度算着有点高…… 最后正解死于常数太大……旁边的lyl用同样的算 ...

  6. 【Bzoj1875】HH去散步

    [Bzoj1875]HH去散步 先说一下边点互化的思路(貌似这种题不多?),以后看见边数少的要死的记得想边点乎化,将无向边变成有向边在考虑边之间的可达性,如果边x的终点是边y的起点(前提不是同一条边) ...

  7. POJ3080 Blue Jeans 题解 KMP算法

    题目链接:http://poj.org/problem?id=3080 题目大意:给你N个长度为60的字符串(N<=10),求他们的最长公共子串(长度>=3). 题目分析:KMP字符串匹配 ...

  8. SuperSocket AppServer 的两个事件: NewSessionConnected 和 SessionClosed

    订阅事件: appServer.NewSessionConnected += new SessionHandler<AppSession>(appServer_NewSessionConn ...

  9. HTML静态网页---样式属性

    一.背景与前景 1.背景: 2.前景字体: 二.边界和边框 border(表格边框.样式等).margin(表外间距).padding(内容与单元格间距). 三.列表与方块 width.height. ...

  10. 基于@AspectJ注解配置切面与基于XML配置切面

    1. Waiter目标类 package com.smart.aop.advice.pointcut; public class Waiter { public void greetTo(String ...