在Model层建立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);
}
}
}
} 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;
}
}
}
}#>

在编写T4模版

<#@ 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" #>
<#@ include file="ModelAuto.ttinclude"#>
<# var manager = new Manager(Host, GenerationEnvironment, true) { OutputPath = Path.GetDirectoryName(Host.TemplateFile)}; #>
<#
string connectionString = "Data Source=.;Initial Catalog=MiniProfilerDemo;User ID=sa;Password=tfc063318;";
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"]+".cs");
#>
//----------<#=row["TABLE_NAME"].ToString()#>开始---------- using System;
namespace MyProject.Entities
{
/// <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>
/// <#= dc.DataType.Name #>:<#=ds2.Tables[0].Rows[0].ItemArray[2]#>
/// </summary>
public <#= dc.DataType.Name #> <#= dc.ColumnName #> {get;set;}
<# } #>
}
} //----------<#=row["TABLE_NAME"].ToString()#>结束---------- <# manager.EndBlock(); #> <#
} #> <#
manager.Process(true);
#>

注意:T4模版中需要修改数据库连接字符串命名空间

保存,就可以生成MSSQL数据库的实体类啦!!

T4模版自动生成MSSQL实体类的更多相关文章

  1. Mysql逆向工程效率神器之使用IDE自动生成Java实体类

    Mysql逆向工程效率神器之使用IDE自动生成Java实体类 简介:实战使用IDE根据Mysql自动生成java pojo实体类 1.IDEA连接数据库 菜单View→Tool Windows→Dat ...

  2. 小D课堂-SpringBoot 2.x微信支付在线教育网站项目实战_2-6.Mysql逆向工程效率神器之使用IDE自动生成Java实体类

    笔记 6.Mysql逆向工程效率神器之使用IDE自动生成Java实体类     简介:实战使用IDE根据Mysql自动生成java pojo实体类                  1.IDEA连接数 ...

  3. MyEclipse自动生成hibernate实体类和配置文件攻略

    步骤1:找到导航栏里面的window--showView然后输入db brower,打开数据库浏览窗口步骤2:在数据库浏览窗口里只有一个Myeclipse自带的数据库,该数据没有用,我们在空白的地方右 ...

  4. AndroidStudio中安装可自动生成json实体类的jar包

    第一步:安装gsonjar包, 这样gson包就下载好了.接下来安装能自动生成实体类的插件: 接下来不要忘了重启: 重启后,就可以通过自定义的快捷键 alt+shift+s来打开generate,从而 ...

  5. SQL自动生成java实体类POJO

    前言 当我们设计完成数据库之后,通常需要创建对应的实体类,有的称为Entity,有的称为DO,都是一个意思,而自己一个个去写非常的麻烦,所以麻烦的时候就需要相应的自动工具类解决这样的麻烦.超级方便~ ...

  6. 使用T4模板动态生成NPoco实体类

    这是一个妥妥的NPoco类,这是我们在工作开发中,手动去写这个实体类,属实非常心累,字段少无所谓一次两次,数量多了,字段多了,就心态裂开

  7. Mybatis Generator代码自动生成(实体类、dao层、映射文件)

    写了一段时间增删改查有点厌烦,自己找了下网上的例子鼓捣了下自动生成. 首先得有一个配置文件: generatorConfig.xml <?xml version="1.0" ...

  8. IDEA 自动生成Hibernate实体类和Mapping文件

    一.新建工程Demo(如果选的时候勾选了hibernate,IDEA会自动下载Hibernate包,不需要手动导入) 二.导入相关包 Mysql && Hibernate 三.添加Hi ...

  9. (转)MyEclipse自动生成Hibernate实体类, oracle篇

    转自http://blog.csdn.net/hejinwei_1987/article/details/9465529 1.打开 windows -> Open Perspective -&g ...

随机推荐

  1. 007_Chrome的Waterfall详解

    一. 浏览器根据html中外连资源出现的顺序,依次放入队列(Queue),然后根据优先级确定向服务器获取资源的顺序.同优先级的资源根据html中出现的先后顺序来向服务器获取资源 Queueing. 出 ...

  2. 030_CORS深究

    在日常的项目开发时会不可避免的需要进行跨域操作,而在实际进行跨域请求时,经常会遇到类似 No 'Access-Control-Allow-Origin' header is present on th ...

  3. mysql设计表时注意事项

    说明:本文是对项目过程中的一些要求的简单汇总整理,主要是供个人本身参考... 一.表设计 1. 在创建表结构时,表名.字段需要见名知意,不采用拼音 create table  `tb_abc` (   ...

  4. Vuex与axios介绍

    Vuex集中式状态管理里架构 axios (Ajax) Vuex集中式状态管理架构 -简单介绍: vuex是一个专门为Vue.js设计的集中式状态管理架构. 我们把它理解为在data中需要共享给其他组 ...

  5. php如何实现图片点击下载,并保存本地?-----本例子为二维码的生成图片,并支持点击下载

    ### 今天因为工作需要,完成了一个二维码的生成图片,并支持点击下载的 ### 控制器文件,相关代码 // 生成二维码 $url = action('Apih5\\VersionController@ ...

  6. linux杀死僵尸进程

    用下面的命令找出僵死进程 ps -A -o stat,ppid,pid,cmd | grep -e '^[Zz]' 命令注解: -A 参数列出所有进程 -o 自定义输出字段 我们设定显示字段为 sta ...

  7. 图解Metrics, tracing, and logging

    Logging,Metrics 和 Tracing   最近在看Gophercon大会PPT的时候无意中看到了关于Metrics,Tracing和Logging相关的一篇文章,凑巧这些我基本都接触过, ...

  8. mysql·事务挂起

          当开启事务后,程序挂了而事务没有提交,那么会被锁住,报错:连接超时,但不影响查询. 下面操作需要权限     一.查询现在被占用的锁信息 select * from information ...

  9. 在Winform开发框架中实现对数据库的加密支持(转)

    在很多情况下,我们需要对数据库进行加密,特别是Access数据库.Sqlite数据库,这些直接部署在客户端的数据,因为数据也是客户的资产,数据库总是存在很多相关的秘密或者重要的业务数据,所以一般来说, ...

  10. Nginx(./configure --help)

    # ./configure --help --help print this message --prefix=PATH set installation prefix --sbin-path=PAT ...