新建类库,右键添加 "文本模板"

添加完成之后生成如下后缀为 tt的文件:

双击文件:TextTemplate_Test.tt 文件打开,替换代码如下

 <#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Data" #>
<#@ assembly name="System.xml" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Data.SqlClient" #>
<#@ import namespace="System.Data" #>
<#@ include file="ModelAuto.ttinclude"#>
<#@ output extension=".cs" #> <# var manager = new Manager(Host, GenerationEnvironment, true) { OutputPath = Path.GetDirectoryName(Host.TemplateFile)}; #>
<#
//数据库连接
string connectionString ="Data Source=127.0.0.1;Initial Catalog=TestDB;User ID=sa;Password=123456;";
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();
//查询字段
string propQuery = "SELECT 表名=sobj.name,字段名=scol.name,字段说明=sprop.[value] FROM syscolumns as scol inner join sys.sysobjects as sobj on scol.id=sobj.id and sobj.xtype='U' and sobj.name<>'dtproperties' left join sys.extended_properties as sprop on scol.id=sprop.major_id and scol.colid=sprop.minor_id where sobj.name='@tableName' and scol.name='@columnName'";
SqlCommand command2 = new SqlCommand(propQuery,conn);
SqlDataAdapter ad2 = new SqlDataAdapter(command2);
System.Data.DataSet ds2 = new DataSet();
#> <# foreach(System.Data.DataRow row in schema.Rows) { #>
<# manager.StartBlock(row["TABLE_NAME"].ToString()+".cs"); #>
using System; namespace Entity.Model
{
/// <summary>
/// 实体类:<#= row["TABLE_NAME"].ToString() #>
/// </summary>
[Serializable]
public class <#= row["TABLE_NAME"].ToString() #>
{
<#
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)
{
#>
<#
ds2.Tables.Clear();
command2.CommandText = propQuery.Replace("@tableName",row["TABLE_NAME"].ToString());
command2.CommandText = command2.CommandText.Replace("@columnName",dc.ColumnName);
ad2.Fill(ds2);
#> ///<summary>
///<#= manager.TransFromSqlType(dc.DataType.Name) #>:<#=ds2.Tables[0].Rows[0].ItemArray[2]#>
///</summary>
public <#= manager.TransFromSqlType(dc.DataType.Name) #> <#= dc.ColumnName #> { get; set; }
<#}#>
}
} <# manager.EndBlock(); #> <#}#> <#manager.Process(true);#>

需要更换几个配置的地方:

1,设置数据库连接,找到该段代码:string connectionString ="Data Source=127.0.0.1;Initial Catalog=TestDB;User ID=sa;Password=123456;";  替换你要连接的数据库即可;

2,设置命名空间,找到代码:namespace Entity.Model {....} ,将该处的命名空间替换你要的即可;

3,相同目录下添加代码自动生成逻辑文件,文件名字为:ModelAuto.ttinclude

文件内容如下,

 <#@ assembly name="System.Core"#>
<#@ assembly name="EnvDTE"#>
<#@ import namespace="System.Collections.Generic"#>
<#@ import namespace="System.IO"#>
<#@ import namespace="System.Text"#>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating"#> <#+ class Manager
{
public struct Block {
public String Name;
public int Start, Length;
} public List<Block> blocks = new List<Block>();
public Block currentBlock;
public Block footerBlock = new Block();
public Block headerBlock = new Block();
public ITextTemplatingEngineHost host;
public ManagementStrategy strategy;
public StringBuilder template;
public String OutputPath { get; set; } public Manager(ITextTemplatingEngineHost host, StringBuilder template, bool commonHeader) {
this.host = host;
this.template = template;
OutputPath = String.Empty;
strategy = ManagementStrategy.Create(host);
} public void StartBlock(String name) {
currentBlock = new Block { Name = name, Start = template.Length };
} public void StartFooter() {
footerBlock.Start = template.Length;
} public void EndFooter() {
footerBlock.Length = template.Length - footerBlock.Start;
} public void StartHeader() {
headerBlock.Start = template.Length;
} public void EndHeader() {
headerBlock.Length = template.Length - headerBlock.Start;
} public void EndBlock() {
currentBlock.Length = template.Length - currentBlock.Start;
blocks.Add(currentBlock);
} public void Process(bool split) {
String header = template.ToString(headerBlock.Start, headerBlock.Length);
String footer = template.ToString(footerBlock.Start, footerBlock.Length);
blocks.Reverse();
foreach(Block block in blocks) {
String fileName = Path.Combine(OutputPath, block.Name);
if (split) {
String content = header + template.ToString(block.Start, block.Length) + footer;
strategy.CreateFile(fileName, content);
template.Remove(block.Start, block.Length);
} else {
strategy.DeleteFile(fileName);
}
}
} /// <summary>
/// SQL[不完善,需要的自己改造]
/// 更换字段类型
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public string TransFromSqlType(string type)
{
if (string.IsNullOrEmpty(type))
{
return string.Empty;
}
if (string.Equals(type, "Boolean", StringComparison.OrdinalIgnoreCase))
{
return "bool";
}
else if (string.Equals(type, "Int32", StringComparison.OrdinalIgnoreCase))
{
return "int";
}
else if (string.Equals(type, "Int64", StringComparison.OrdinalIgnoreCase))
{
return "long";
}
else if (string.Equals(type, "String", StringComparison.OrdinalIgnoreCase))
{
return "string";
}
else if(string.Equals(type, "Byte", StringComparison.OrdinalIgnoreCase))
{
return "byte";
}
else if (string.Equals(type, "Decimal", StringComparison.OrdinalIgnoreCase))
{
return "decimal";
}
else if (string.Equals(type, "datetime", StringComparison.OrdinalIgnoreCase))
{
return "DateTime";
}
return "string";
} } class ManagementStrategy
{
internal static ManagementStrategy Create(ITextTemplatingEngineHost host) {
return (host is IServiceProvider) ? new VSManagementStrategy(host) : new ManagementStrategy(host);
} internal ManagementStrategy(ITextTemplatingEngineHost host) { } internal virtual void CreateFile(String fileName, String content) {
File.WriteAllText(fileName, content);
} internal virtual void DeleteFile(String fileName) {
if (File.Exists(fileName))
File.Delete(fileName);
}
} class VSManagementStrategy : ManagementStrategy
{
private EnvDTE.ProjectItem templateProjectItem; internal VSManagementStrategy(ITextTemplatingEngineHost host) : base(host) {
IServiceProvider hostServiceProvider = (IServiceProvider)host;
if (hostServiceProvider == null)
throw new ArgumentNullException("Could not obtain hostServiceProvider"); EnvDTE.DTE dte = (EnvDTE.DTE)hostServiceProvider.GetService(typeof(EnvDTE.DTE));
if (dte == null)
throw new ArgumentNullException("Could not obtain DTE from host"); templateProjectItem = dte.Solution.FindProjectItem(host.TemplateFile);
} internal override void CreateFile(String fileName, String content) {
base.CreateFile(fileName, content);
((EventHandler)delegate { templateProjectItem.ProjectItems.AddFromFile(fileName); }).BeginInvoke(null, null, null, null);
} internal override void DeleteFile(String fileName) {
((EventHandler)delegate { FindAndDeleteFile(fileName); }).BeginInvoke(null, null, null, null);
} private void FindAndDeleteFile(String fileName) {
foreach(EnvDTE.ProjectItem projectItem in templateProjectItem.ProjectItems) {
if (projectItem.get_FileNames() == fileName) {
projectItem.Delete();
return;
}
}
}
}#>

接下来就是见证奇迹的时刻,选中 TextTemplate_Test.tt 文件 按 Ctrl+C即可(每次更新实体类时,需要先修改一下模板文件,随便修改什么地方,按个空格也可以),生成模板代码如下:

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

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

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

  2. c# T4模板生成实体类(sqlserver)

    1.用vs新建tt文件. 2.tt文件保存就自动运行 3.tt文件代码如下,设置生成cs文件的命名空间和生成地址 <#@ template language="C#" hos ...

  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. Codeforces_338_D

    http://codeforces.com/problemset/problem/338/D 中国剩余定理的应用,思路是确定可能符合的最小行和最小列,然后判断是否符合.若不符合则后面的(最小的倍数)也 ...

  2. Codeforces_490_E

    http://codeforces.com/problemset/problem/490/E dfs,过程要注意细节,特别是当前位置取了与上个数当前位置相同是,若后面不符合条件,则当前位置要重置'?' ...

  3. Codeforces Round #600 (Div. 2) E. Antenna Coverage

    Codeforces Round #600 (Div. 2) E. Antenna Coverage(dp) 题目链接 题意: m个Antenna,每个Antenna的位置是\(x_i\),分数是\( ...

  4. DG参数 LOG_ARCHIVE_DEST_n

    DG参数 LOG_ARCHIVE_DEST_n This chapter provides reference information for the attributes of the LOG_AR ...

  5. LeetCode 127. Word Ladder 单词接龙(C++/Java)

    题目: Given two words (beginWord and endWord), and a dictionary's word list, find the length of shorte ...

  6. JVM解毒——JVM与Java体系结构

    你是否也遇到过这些问题? 运行线上系统突然卡死,系统无法访问,甚至直接OOM 想解决线上JVM GC问题,但却无从下手 新项目上线,对各种JVM参数设置一脸懵逼,直接默认,然后就JJ了 每次面试都要重 ...

  7. c#学习笔记之委托

    委托 最近自己在调试C#项目,发现经常可以看到委托和lambda表达式,各种花里胡哨的写法把我给整的云里雾里的,于是自己特意花了一点功夫来整理关于delegate的相关知识,方便自己日后查阅. 何为委 ...

  8. php gettype()函数

      gettype() 会根据 参数类型返回值: boolean:表示变量为布尔类型 integer:表示变量为整数类型 double :表示变量为float类型(历史原因) string:表示变量为 ...

  9. vue学习(四)登陆、注册、首页模板页区分

    按照上面文章配置完毕后,会发现有个问题,我登陆页面.注册页面是不需要视图页的. 开始配置路由 重新配置main.js 引入 import App from './App' //引入vue组件 更改启动 ...

  10. 服务器安全之iptables

    服务器安全之iptables iptables防火墙简介 Netfilter/Iptables(以下简称Iptables)是unix/linux自带的一款优秀且开放源代码的安全自由的基于包过滤的防火墙 ...