MysqlDbhelper.ttinclude

<#@ assembly name="System.Core"#>
<#@ assembly name="System.Data"#>
<#@ assembly name="MySql.Data"#> <#@ import namespace="System" #>
<#@ import namespace="System.Data" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="MySql.Data.MySqlClient" #>
<#+
public class EntityHelper
{
public static List<Entity> GetEntities(string connectionString, List<string> databases)
{
var list = new List<Entity>();
var conn = new MySqlConnection(connectionString);
try
{
conn.Open();
var dbs = string.Join("','", databases.ToArray());
var cmd = string.Format(@"SELECT `information_schema`.`COLUMNS`.`TABLE_SCHEMA`
,`information_schema`.`COLUMNS`.`TABLE_NAME`
,`information_schema`.`COLUMNS`.`COLUMN_NAME`
,`information_schema`.`COLUMNS`.`DATA_TYPE`
,`information_schema`.`COLUMNS`.`COLUMN_COMMENT`
FROM `information_schema`.`COLUMNS`
WHERE `information_schema`.`COLUMNS`.`TABLE_SCHEMA` IN ('{0}') ", dbs);
using (var reader = MySqlHelper.ExecuteReader(conn, cmd))
{
while (reader.Read())
{
var db = reader["TABLE_SCHEMA"].ToString();
var table = reader["TABLE_NAME"].ToString();
var column = reader["COLUMN_NAME"].ToString();
var type = reader["DATA_TYPE"].ToString();
var comment = reader["COLUMN_COMMENT"].ToString();
var entity = list.FirstOrDefault(x => x.EntityName == table);
if(entity == null)
{
entity = new Entity(table);
entity.Fields.Add(new Field
{
Name = column,
Type = GetCLRType(type),
Comment = comment
}); list.Add(entity);
}
else
{
entity.Fields.Add(new Field
{
Name = column,
Type = GetCLRType(type),
Comment = comment
});
}
}
}
}
finally
{
conn.Close();
} return list;
} public static string GetCLRType(string dbType)
{
switch(dbType)
{
case "tinyint":
case "smallint":
case "mediumint":
case "int":
case "integer":
return "int";
case "double":
return "double";
case "float":
return "float";
case "decimal":
return "decimal";
case "numeric":
case "real":
return "decimal";
case "bit":
return "bool";
case "date":
case "time":
case "year":
case "datetime":
case "timestamp":
return "DateTime";
case "tinyblob":
case "blob":
case "mediumblob":
case "longblog":
case "binary":
case "varbinary":
return "byte[]";
case "char":
case "varchar":
case "tinytext":
case "text":
case "mediumtext":
case "longtext":
return "string";
case "point":
case "linestring":
case "polygon":
case "geometry":
case "multipoint":
case "multilinestring":
case "multipolygon":
case "geometrycollection":
case "enum":
case "set":
default:
return dbType;
}
}
} public class Entity
{
public Entity()
{
this.Fields = new List<Field>();
} public Entity(string name)
: this()
{
this.EntityName = name;
} public string EntityName { get;set; }
public List<Field> Fields { get;set; }
} public class Field
{
public string Name { get;set; }
public string Type { get;set; }
public string Comment { get;set; }
}
#>

mysqlManager.ttinclude

<#@ assembly name="System.Core"#>
<#@ assembly name="System.Data.Linq"#>
<#@ assembly name="EnvDTE"#>
<#@ assembly name="System.Xml"#>
<#@ assembly name="System.Xml.Linq"#>
<#@ import namespace="System"#>
<#@ import namespace="System.CodeDom"#>
<#@ import namespace="System.CodeDom.Compiler"#>
<#@ import namespace="System.Collections.Generic"#>
<#@ import namespace="System.Data.Linq"#>
<#@ import namespace="System.Data.Linq.Mapping"#>
<#@ import namespace="System.IO"#>
<#@ import namespace="System.Linq"#>
<#@ import namespace="System.Reflection"#>
<#@ import namespace="System.Text"#>
<#@ import namespace="System.Xml.Linq"#>
<#@ import namespace="Microsoft.VisualStudio.TextTemplating"#>
<#+ // Manager class records the various blocks so it can split them up
class Manager {
private class Block {
public String Name;
public int Start, Length;
} private Block currentBlock;
private List<Block> files = new List<Block>();
private Block footer = new Block();
private Block header = new Block();
private ITextTemplatingEngineHost host;
private StringBuilder template;
protected List<String> generatedFileNames = new List<String>(); public static Manager Create(ITextTemplatingEngineHost host, StringBuilder template) {
return (host is IServiceProvider) ? new VSManager(host, template) : new Manager(host, template);
} public void StartNewFile(String name) {
if (name == null)
throw new ArgumentNullException("name");
CurrentBlock = new Block { Name = name };
} public void StartFooter() {
CurrentBlock = footer;
} public void StartHeader() {
CurrentBlock = header;
} public void EndBlock() {
if (CurrentBlock == null)
return;
CurrentBlock.Length = template.Length - CurrentBlock.Start;
if (CurrentBlock != header && CurrentBlock != footer)
files.Add(CurrentBlock);
currentBlock = null;
} public virtual void Process(bool split) {
if (split) {
EndBlock();
String headerText = template.ToString(header.Start, header.Length);
String footerText = template.ToString(footer.Start, footer.Length);
String outputPath = Path.GetDirectoryName(host.TemplateFile);
files.Reverse();
foreach(Block block in files) {
String fileName = Path.Combine(outputPath, block.Name);
String content = headerText + template.ToString(block.Start, block.Length) + footerText;
generatedFileNames.Add(fileName);
CreateFile(fileName, content);
template.Remove(block.Start, block.Length);
}
}
} protected virtual void CreateFile(String fileName, String content) {
if (IsFileContentDifferent(fileName, content))
File.WriteAllText(fileName, content);
} public virtual String GetCustomToolNamespace(String fileName) {
return null;
} public virtual String DefaultProjectNamespace {
get { return null; }
} protected bool IsFileContentDifferent(String fileName, String newContent) {
return !(File.Exists(fileName) && File.ReadAllText(fileName) == newContent);
} private Manager(ITextTemplatingEngineHost host, StringBuilder template) {
this.host = host;
this.template = template;
} private Block CurrentBlock {
get { return currentBlock; }
set {
if (CurrentBlock != null)
EndBlock();
if (value != null)
value.Start = template.Length;
currentBlock = value;
}
} private class VSManager: Manager {
private EnvDTE.ProjectItem templateProjectItem;
private EnvDTE.DTE dte;
private Action<String> checkOutAction;
private Action<IEnumerable<String>> projectSyncAction; public override String DefaultProjectNamespace {
get {
return templateProjectItem.ContainingProject.Properties.Item("DefaultNamespace").Value.ToString();
}
} public override String GetCustomToolNamespace(string fileName) {
return dte.Solution.FindProjectItem(fileName).Properties.Item("CustomToolNamespace").Value.ToString();
} public override void Process(bool split) {
if (templateProjectItem.ProjectItems == null)
return;
base.Process(split);
projectSyncAction.EndInvoke(projectSyncAction.BeginInvoke(generatedFileNames, null, null));
} protected override void CreateFile(String fileName, String content) {
if (IsFileContentDifferent(fileName, content)) {
CheckoutFileIfRequired(fileName);
File.WriteAllText(fileName, content);
}
} internal VSManager(ITextTemplatingEngineHost host, StringBuilder template)
: base(host, template) {
var hostServiceProvider = (IServiceProvider) host;
if (hostServiceProvider == null)
throw new ArgumentNullException("Could not obtain IServiceProvider");
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);
checkOutAction = (String fileName) => dte.SourceControl.CheckOutItem(fileName);
projectSyncAction = (IEnumerable<String> keepFileNames) => ProjectSync(templateProjectItem, keepFileNames);
} private static void ProjectSync(EnvDTE.ProjectItem templateProjectItem, IEnumerable<String> keepFileNames) {
var keepFileNameSet = new HashSet<String>(keepFileNames);
var projectFiles = new Dictionary<String, EnvDTE.ProjectItem>();
var originalFilePrefix = Path.GetFileNameWithoutExtension(templateProjectItem.get_FileNames()) + ".";
foreach(EnvDTE.ProjectItem projectItem in templateProjectItem.ProjectItems)
projectFiles.Add(projectItem.get_FileNames(), projectItem); // Remove unused items from the project
foreach(var pair in projectFiles)
if (!keepFileNames.Contains(pair.Key) && !(Path.GetFileNameWithoutExtension(pair.Key) + ".").StartsWith(originalFilePrefix))
pair.Value.Delete(); // Add missing files to the project
foreach(String fileName in keepFileNameSet)
if (!projectFiles.ContainsKey(fileName))
templateProjectItem.ProjectItems.AddFromFile(fileName);
} private void CheckoutFileIfRequired(String fileName) {
var sc = dte.SourceControl;
if (sc != null && sc.IsItemUnderSCC(fileName) && !sc.IsItemCheckedOut(fileName))
checkOutAction.EndInvoke(checkOutAction.BeginInvoke(fileName, null, null));
}
}
} #>

MysqlModel.tt

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ include file="mysqlManager.ttinclude" #>
<#@ include file="MysqlDbhelper.ttinclude" #>
<#
// 是否是WCF服务模型
bool serviceModel = false; // 数据库连接
var connectionString = @"server=127.0.0.1;uid=root;pwd=sa;charset=utf8;"; // 需要解析的数据库
var database = new List<string> { "student" }; // 文件版权信息
var copyright = DateTime.Now.Year + " xxxx Enterprises All Rights Reserved";
var version = Environment.Version;
var author = "auto generated by T4"; var manager = Manager.Create(Host, GenerationEnvironment);
var entities = EntityHelper.GetEntities(connectionString, database); foreach(Entity entity in entities)
{
manager.StartNewFile(entity.EntityName + ".cs");
#>
//-----------------------------------------------------------------------
// <copyright file=" <#= entity.EntityName #>.cs" company="xxxx Enterprises">
// * Copyright (C) <#= copyright #>
// * version : <#= version #>
// * author : <#= author #>
// * FileName: <#= entity.EntityName #>.cs
// * history : Created by T4 <#= DateTime.Now #>
// </copyright>
//-----------------------------------------------------------------------
using System;
<# if(serviceModel)
{
#>
using System.Runtime.Serialization;
<#
}
#> namespace Console4Test
{
/// <summary>
/// <#= entity.EntityName #> Entity Model
/// </summary>
[Serializable]
<# if(serviceModel)
{
#>
[DataContract]
<#
}
#>
public class <#= entity.EntityName #>
{
<#
for(int i = ; i < entity.Fields.Count; i++)
{
if(i ==){
#> /// <summary>
/// <#= entity.Fields[i].Comment #>
/// </summary>
<# if(serviceModel)
{
#>
[DataMember]
<#
}
#>
public <#= entity.Fields[i].Type #> <#= entity.Fields[i].Name #> { get; set; }
<#
}
else{
#>
/// <summary>
/// <#= entity.Fields[i].Comment #>
/// </summary>
<# if(serviceModel)
{
#>
[DataMember]
<#
}
#>
public <#= entity.Fields[i].Type #> <#= entity.Fields[i].Name #> { get; set; }
<# }
}
#>
}
}
<#
manager.EndBlock();
} manager.Process(true);
#>

T4模版 mysql的更多相关文章

  1. ASP.NET MVC5+EF6+EasyUI 后台管理系统(29)-T4模版

    系列目录 本节不再适合本系统,在58,59节已经重构.请超过本节 这讲适合所有的MVC程序 很荣幸,我们的系统有了体验的地址了.演示地址 之前我们发布了一个简单的代码生成器,其原理就是读取数据库的表结 ...

  2. SubSonic3.0 Demo1.0——应用了T4模版可减少开发过程中70%以上的代码量以及80%以上的出错率

    应网友的要求,抽了点时间写了这个Demo,希望对2.2版想升级到3.0的朋友或正在使用3.0的朋友有所帮助.大家在使用Demo过程中如果发现什么问题或有什么建议,可以直接将Bug提交给我或告诉我,我会 ...

  3. T4模版基础例子

    <#@ template debug="false" hostspecific="true" language="C#" #> ...

  4. EF架构~在T4模版中为所有属性加默认值

    回到目录 在项目开发过程中,出现了一个问题,就是新添加一个非空字段后,原来的程序逻辑需要被重新修改,即将原来的字段添加到程序里,这种作法是非常不提倡的,所以,我通过T4模版将原来的实体类小作修改,解决 ...

  5. EF架构~在T4模版中自定义属性的getter和setter

    回到目录 T4模版为我们在ORM操作上提供了便捷,它很方便的可以对实体进行全局性的修改,之前我介绍过通过T4来为属性加默认性,而今天我主要告诉大家如何使用T4模版将getter,setter块改为自己 ...

  6. T4教程1 T4模版引擎之基础入门

    T4模版引擎之基础入门   额,T4好陌生的名字,和NuGet一样很悲催,不为世人所熟知,却又在背后默默无闻的奉献着,直到现在我们项目组的人除了我之外,其它人还是对其豪无兴趣,基本上是连看一眼都懒得看 ...

  7. T4教程2 T4模版引擎之生成数据库实体类

    T4模版引擎之生成数据库实体类   在通过T4模版引擎之基础入门 对T4有了初步印象后,我们开始实战篇.T4模板引擎可以当做一个代码生成器,代码生成器的职责当然是用来生成代码(这不是废话吗).而这其中 ...

  8. T4模版生成多个实体文件时,提示找不到 Host

    T4模版生成多个实体文件时,提示找不到 Host 使用以下方法,把hostspecific改为true就可以了 hostspecific:有效值true.false,默认为false.如果将此特性的值 ...

  9. 黄聪:VS2010开发T4模版引擎之基础入门

    原文:http://www.cnblogs.com/lzrabbit/archive/2012/07/15/2591085.html 额,T4好陌生的名字,和NuGet一样很悲催,不为世人所熟知,却又 ...

随机推荐

  1. C# Note8: 设计模式全解

    前言——资源说明 目前网上设计模式的介绍可谓非常之多(各种编程语言的版本),其中不乏精细之作,本文的目的在于搜集和整理C#或C++的设计模式,毕竟思想还是共通的! 设计模式的分类 创建型模式,共五种: ...

  2. 解决方法:CentOS7用yum安装软件显示错误:cannot find a valid baseurl for repo: base/7/x86_64

    在Linux学习中,发现使用yum安装软件出现以下的错误: 百度了各种方法,很多人也发现光是修改REBOOT=yes也没用,多次进行挂载.修改网卡配置文件.重置IP地址.重启网络.创建又删除配置文件的 ...

  3. HDU 1074 Doing Homework(经典状压dp)

    题目链接  Doing Homework        Ignatius has just come back school from the 30th ACM/ICPC. Now he has a ...

  4. c++数字和字符串的转换

    1  利用stringstream 添加头文件 #include<sstream> 数字转字符串 #include <string>   #include <sstrea ...

  5. codeforces285C

    Building Permutation CodeForces - 285C Permutation p is an ordered set of integers p1,  p2,  ...,  p ...

  6. 前端es6基础语法

    1.let.const.var var是声明全局的变量,作用域是全局,const是声明全局的常量,不能修改,而let是块级变量只在当前声明的作用域中生效: { var a = 10; let b = ...

  7. Hibernate中的Entity类之间的继承关系之一MappedSuperclass

    在hibernate中,Entity类可以继承Entity类或非Entity类.但是,关系数据库表之间不存在继承的关系.那么在Entity类之间的继承关系,在数据库表中如何表示呢? Hibernate ...

  8. iptables防火墙的原理及应用

    简介 (netfilter, 位于Linux内核中的包过滤功能体系  ,称为Linux防火墙的“内核态”) iptables防火墙工作在网络层,针对TCP/IP数据包实施过滤和限制,iptables防 ...

  9. linux-shell系列2-机器巡检

    #!/bin/bash#主机信息每日巡检NETWORK=`ip a|grep 2:|awk -F':' '{print $2}'` IPADDR=$(ifconfig $NETWORK|grep 'i ...

  10. puppet的常用语法

    检查语法错误 puppet parser validate xx.pp 在客户端测试但是不应用 puppet agent --test --noop 基于安全的考虑,使用预签名证书 puppet ce ...