c# T4模板生成实体类(sqlserver)
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)的更多相关文章
- c# 使用T4模板生成实体类(sqlserver)
新建类库,右键添加 "文本模板" 添加完成之后生成如下后缀为 tt的文件: 双击文件:TextTemplate_Test.tt 文件打开,替换代码如下 <#@ templat ...
- {T4模板}C# Net MVC+SqlServer=T4模板生成实体类并操作数据(DbHelper+DBManage)
1.ConnectionString,数据库链接 Web.config <configuration> <connectionStrings> <!-- 数据库 SQL ...
- C# T4 模板 数据库实体类生成模板(带注释,娱乐用)
说明:..,有些工具生成实体类没注释,不能和SqlServer的MS_Description属性一起使用,然后照着网上的资源,随便写了个生成模板,自娱自乐向,其实卵用都没有参考教程 1.htt ...
- 使用T4模板生成POCO类
为什么叫T4?因为简写为4个T. T4(Text Template Transformation Toolkit)是微软官方在VisualStudio 2008中开始使用的代码生成引擎.在 Visua ...
- T4模板根据DB生成实体类
1.前言 为什么会有这篇文章了,最近看到了一些框架,里面要写的代码太多了,故此就想偷懒,要是能写出一个T4模板,在数据库添加表后,根据模板就可以自动生成了类文件了,这样多好,心动不如行动.记得使用T4 ...
- T4模板_根据DB生成实体类
为了减少重复劳动,可以通过T4读取数据库表结构,生成实体类,用下面的实例测试了一下 1.首先创建一个项目,并添加文本模板: 2.添加 文本模板: 3.向T4文本模板文件添加代码: <#@ tem ...
- 使用T4模板生成MySql数据库实体类
注:本文系作者原创,但可随意转载. 现在呆的公司使用的数据库几乎都是MySQL.编程方式DatabaseFirst.即先写数据库设计,表设计按照规范好的文档写进EXCEL里,然后用公司的宏,生成建表脚 ...
- 使用T4为数据库自动生成实体类
T4 (Text Template Transformation Toolkit) 是一个基于模板的代码生成器.使用T4你可以通过写一些ASP.NET-like模板,来生成C#, T-SQL, XML ...
- 懒人小工具:T4生成实体类Model,Insert,Select,Delete以及导出Excel的方法
由于最近公司在用webform开发ERP,用到大量重复机械的代码,之前写了篇文章,懒人小工具:自动生成Model,Insert,Select,Delete以及导出Excel的方法,但是有人觉得这种方法 ...
随机推荐
- WebForms UnobtrusiveValidationMode 需要“jquery”ScriptResourceMapping 的解决方法
问题描述:VS2012使用验证控件出现“ WebForms UnobtrusiveValidationMode 需要“jquery”ScriptResourceMapping.请添加一个名为 jque ...
- 阿里云oss上传图片报错,The OSS Access Key Id you provided does not exist in our records.解决方法
vue项目 1.安装OSS的Node SDK npm install ali-oss --save 2.参考官方提示https://help.aliyun.com/document_detail/11 ...
- SDUT-3347_数据结构实验之数组三:快速转置
数据结构实验之数组三:快速转置 Time Limit: 1000 ms Memory Limit: 65536 KiB Problem Description 转置运算是一种最简单的矩阵运算,对于一个 ...
- 模板—tarjan求割点
int dfn[MAXN],low[MAXN],cnt,root; bool iscut[MAXN]; void tarjan(int x) { dfn[x]=low[x]=++cnt; ; for( ...
- LRJ-Example-06-04-Uva11988
单向链表的元素存放在数组s[]中,next指针存放在数组next[]中. 链表初始为空,next[0] == 0 代表链表结尾,类似NULL指针,在最后打印链表的时候作为for循环结束的条件. 依次插 ...
- win7 debug 工具
x86 处理器中的 CS 与 IP 寄存器介绍与调试: http://blog.sina.com.cn/s/blog_54f82cc2010121yj.html https://www.jianshu ...
- CodeForces 1243"Character Swap (Hard Version)"(multimap)
传送门 •前置知识-multimap的用法 $multimap$ 与 $map$ 的区别在于一个 $key$ 可以对应几个值: 对于 $map$ 而言,一个 $key$ 只能对应一个值,并且按照 $k ...
- git clone出现Permission denied (publickey)解决办法
一.错误 git clone git@gitee.com:wangzaiplus/xxx.git, 出现Permission denied (publickey) 二.原因 无权限, 未将公钥添加至G ...
- 【codeforces 764B】Timofey and cubes
time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard ou ...
- python基础十一之装饰器进阶
函数的双下划线方法 def hahahha(): """测试函数""" print('zxc') print(hahahha.__name_ ...