T4 模板生成实体

此文主要方便自己查找

<#@ template language="C#" hostspecific="True" debug="false"#>
<#@include file="../Manager.ttinclude"#>
<#@ assembly name="System" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Data" #>
<#@ assembly name="System.Data.DataSetExtensions" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Data" #>
<#@ import namespace="System.Data.SqlClient" #>
<# var manager = Manager.Create(Host, GenerationEnvironment); #>
<#
  //你的当前model的命名空间
            string ModelNameSpace="Zobo.Entity";
  //你的数据库连接字符串
            string ConnectStr = "";
            SqlConnection MySqlConnection = new SqlConnection(ConnectStr);
            //此sql语句找到你指定数据库下的所有表
            string SelectYourTableNameStr = "SELECT * FROM sys.sysobjects WHERE TYPE='U'";
            SqlDataAdapter MySqlDataAdapter = new SqlDataAdapter(SelectYourTableNameStr, MySqlConnection);
            DataSet MyDataSet = new DataSet();
            MySqlDataAdapter.Fill(MyDataSet, "cacheTable");
            //得到table表
            DataTable MyDataTable = MyDataSet.Tables["cacheTable"];
            int MyDataTableRowsCount = MyDataTable.Rows.Count;
            for (int i = 0; i < MyDataTableRowsCount; i++)
            {
                //表名
                //MyDataTable.Rows[i]["name"].ToString();
                //此sql语句找到你当前表下的所有键值,属性,是否为null,长度。
                string SelectYourKeyStr = "SELECT [col].[COLUMN_NAME] AS keyname,"+
                                          "    [col].[DATA_TYPE] AS keyproperty,"+
                                          "    [col].[CHARACTER_OCTET_LENGTH] AS [length],"+
                                          "    CASE [col].[IS_NULLABLE]"+
                                          "        WHEN 'YES' THEN"+
                                          "            1"+
                                          "        ELSE"+
                                          "            0"+
                                          "    END AS isnullable,"+
                                          "    CASE"+
                                          "        WHEN [ccu].[CONSTRAINT_NAME] IS NOT NULL THEN"+
                                          "            1"+
                                          "        ELSE"+
                                          "            0"+
                                          "    END AS IsPrimaryKey,"+
                                          "    COLUMNPROPERTY(OBJECT_ID('"+ MyDataTable.Rows[i]["name"].ToString() + "'), [col].[COLUMN_NAME], 'IsIdentity') AS IsIdentity"+
                                          "    FROM [INFORMATION_SCHEMA].[COLUMNS] col"+
                                          "     LEFT JOIN [INFORMATION_SCHEMA].[CONSTRAINT_COLUMN_USAGE] ccu"+
                                          "         ON [ccu].[TABLE_NAME] = [col].[TABLE_NAME]"+
                                          "            AND [ccu].[COLUMN_NAME] = [col].[COLUMN_NAME]"+
                                          "            AND [ccu].[CONSTRAINT_NAME] LIKE 'PK_%'"+
                                          " WHERE [col].[TABLE_NAME] = '"+ MyDataTable.Rows[i]["name"].ToString() + "'";

                MySqlDataAdapter = new SqlDataAdapter(SelectYourKeyStr, MySqlConnection);
                 MyDataSet = new DataSet();
                MySqlDataAdapter.Fill(MyDataSet, "cacheTable");
                //得到key表
                DataTable MyKeyTable = MyDataSet.Tables["cacheTable"];
                //tt模板输出文件
                manager.StartNewFile(MyDataTable.Rows[i]["name"].ToString() +".cs");
#>
using System;
using SqlSugar;
namespace <#=ModelNameSpace#>
{
    [SugarTable("<#=MyDataTable.Rows[i]["name"].ToString()#>")]

    
public class <#=MyDataTable.Rows[i]["name"].ToString()#>
    {
<#              for (int keyi = 0; keyi < MyKeyTable.Rows.Count; keyi++)
                {
                   string keypropertyOutput = string.Empty;
                    string isKey=string.Empty;
                        if(MyKeyTable.Rows[keyi]["IsPrimaryKey"].ToString()=="1" && MyKeyTable.Rows[keyi]["IsIdentity"].ToString()=="1"){
                            isKey=", IsPrimaryKey = true, IsIdentity = true";
                        }else if(MyKeyTable.Rows[keyi]["IsPrimaryKey"].ToString()=="1"){
                isKey=", IsPrimaryKey = true";
                         }
                    switch (MyKeyTable.Rows[keyi]["keyproperty"].ToString().ToLower())
                    {
                        case "smallint":
                            keypropertyOutput = "short";
                            break;
                        case "int":
                            keypropertyOutput = "int";
                            break;
                        case "bigint":
                            keypropertyOutput = "long";
                            break;
                        case "real":
                            keypropertyOutput = "float";
                            break;
                        case "float":
                            keypropertyOutput = "double";
                            break;
                        case "money":
                            keypropertyOutput = "decimal";
                            break;
                        case "datetime":
                            keypropertyOutput = "DateTime";
                            break;
                        case "uniqueidentifier":
                            keypropertyOutput = "Guid";
                            break;

                        case "bit":
                            keypropertyOutput = "bool";
                            break;
                        case "tinyint":
                            keypropertyOutput = "byte";
                            break;
                        case "image":
                            keypropertyOutput = "byte[]";
                            break;
                        case "binary":
                            keypropertyOutput = "byte[]";
                            break;
                        default:
                            keypropertyOutput = "string";
                                break;
                    }
                    //可为null且不是string(就是值类型)可以加?
                    if (MyKeyTable.Rows[keyi]["isnullable"].ToString()=="1"&& keypropertyOutput!="string")
                    {
                        if (keypropertyOutput == "byte[]")
                        {
                            keypropertyOutput = "byte?[]";
                        }
                        else
                        {
                            keypropertyOutput = keypropertyOutput + "?";
                        }
                    }
#>
                    [SugarColumn(ColumnName="<#=MyKeyTable.Rows[keyi]["keyname"].ToString()#>" <#=isKey#> )]
                    public  <#=keypropertyOutput#>  <#=MyKeyTable.Rows[keyi]["keyname"].ToString()#>  { get; set; }
<#
                }
#>
    }
}
<#              //代码结束
                manager.EndBlock();
        MySqlConnection.Close();
            }
#>
<# manager.Process(true); #>

Manager.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(0)) + ".";
            foreach(EnvDTE.ProjectItem projectItem in templateProjectItem.ProjectItems)
                projectFiles.Add(projectItem.get_FileNames(0), 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));
        }
    }
} #>
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,864评论 6 494
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,175评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,401评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,170评论 1 286
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,276评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,364评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,401评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,179评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,604评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,902评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,070评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,751评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,380评论 3 319
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,077评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,312评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,924评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,957评论 2 351

推荐阅读更多精彩内容