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

添加完成之后生成如下后缀为 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_734_F

    http://codeforces.com/problemset/problem/734/F x|y + x&y = x+y. #include<iostream> #includ ...

  2. 小白学 Python 数据分析(3):Pandas (二)数据结构 Series

    在家为国家做贡献太无聊,不如跟我一起学点 Python 顺便问一下,你们都喜欢什么什么样的文章封面图,老用这一张感觉有点丑 人生苦短,我用 Python 前文传送门: 小白学 Python 数据分析( ...

  3. 《C# 爬虫 破境之道》:第二境 爬虫应用 — 第五节:小总结带来的优化与重构

    在上一节中,我们完成了一个简单的采集示例.本节呢,我们先来小结一下,这个示例可能存在的问题: 没有做异常处理 没有做反爬应对策略 没有做重试机制 没有做并发限制 …… 呃,看似平静的表面下还是隐藏着不 ...

  4. 前端jQuery日历控件报错 $("#datepicker").datepicker is not a function

    使用日历控件时,前端产生错误: $("#datepicker").datepicker is not a function 问题原因 前端在同一个页面,jQuery引入了两次. 解 ...

  5. eslint报"Extra semicolon"错误的解决

    手机赚钱怎么赚,给大家推荐一个手机赚钱APP汇总平台:手指乐(http://www.szhile.com/),辛苦搬砖之余用闲余时间动动手指,就可以日赚数百元 使用 vue-cli 构建的项目,模版是 ...

  6. JS水仙花数

    题目:3位数==个位立方+十位的立方+百位的立方.这个3位数就是水仙花数.要求打印出所有的水仙花数 <body> <div id=d1> </div> <sc ...

  7. Java笔记---枚举类和注解

    Java笔记---枚举类和注解 一.枚举类 自定义枚举类 方式一:JDK5.0之前自定义枚举类 class Seasons { //1. 声明Seasons对象的属性 private final St ...

  8. 关于广州xx公司对驰骋BPM, 流程引擎表单引擎 常见问题解答

    关于广州xx公司对驰骋BPM, 流程引擎表单引擎 常见问题解答 @驰骋工作流,ccflow周朋 周总早, ccflow 功能很强大,在体验过程中,以下几个问题需沟通下: 先使用.net 再使用java ...

  9. CSGO控制台命令

    转帖: 按下“~”即可开启 使用时先输入参数名 然后按下SPACE空出一格 再输入设定值即可 一般玩家进入游戏都只能用到Client(玩家用参数) 不过...如果你是开LAN GAME的人 就能进阶到 ...

  10. c# 异步编程总结

    异步编程前提 1.学委托 delegate 其中委托中的beginInvoke()和endInvoke()方法必须要会. 2.学习回调函数 (也可以不用,但是一般建议用回调函数中执行endinvoke ...