1.前言

为什么会有这篇文章了,最近看到了一些框架,里面要写的代码太多了,故此就想偷懒,要是能写出一个T4模板,在数据库添加表后,根据模板就可以自动生成了类文件了,这样多好,心动不如行动。记得使用T4模板还是2年前,那个时候听波波老师讲课做我们的最后一个大项目CRM,简简单单的写了一下模板,保存一下,所有的类文件就出来了,当时那个膜拜,油然而生。

T4模板根据DB生成实体类

 同时在工作中,我们公司自己开发的一个ORM,实体类都要自己写,一个数据库表的字段太多,写的真是手抽筋。如果你对T4基础语法不是很了解,可以参考我前面写的一篇文章 T4语法快速入门

2.原理

我们要做的事情是通过数据库表生成实体类。

第一步 我们要查询出当前用户下的所有数据库表。

第二步 查询出数据库表的结构,比如字段的名称,字段的类型,字段的长度大小,是否为空等等。

工作中oracle用的比较多,在这里我就分析oracle和mssql

3.oracle

查询当前用户所有的表。

SELECT TABLE_NAME FROM USER_TABLES;

根据表名查询表结构数据

SELECT A.column_name    字段名,                                                                                      
A.data_type      数据类型,
A.data_length    长度,
A.data_precision 整数位,
A.Data_Scale     小数位,
A.nullable       允许空值,
A.Data_default   缺省值,
B.comments       备注,
A.TABLE_NAME     表名
FROM user_tab_columns A, user_col_comments B
WHERE a.COLUMN_NAME = b.column_name
AND A.Table_Name = B.Table_Name
AND A.Table_Name = 'AFFIXINFO'

 ModelAuto.ttinclude来源与网上,作用是生成一个一个单独的类文件,即xx.cs文件。

<#@ 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(0) == fileName) {
                projectItem.Delete();
                return;
            }
        }
    }
}#>
ModelAuto.ttinclude

相关文章:

  • 2022-12-23
  • 2022-02-01
  • 2021-11-21
  • 2022-12-23
  • 2021-07-28
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-12-09
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-14
  • 2022-12-23
相关资源
相似解决方案