C#通过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=.;Initial Catalog=test;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;
using System.ComponentModel.DataAnnotations;

namespace WebSite.Entity
{
    /// <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[0].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>
        ///<#=ds2.Tables[0].Rows[0].ItemArray[2]#>
        ///</summary>
        [Display(Name = "<#=ds2.Tables[0].Rows[0].ItemArray[2]#>")]
        public <#= manager.TransFromSqlType(dc.DataType.Name) #> <#= dc.ColumnName #> { get; set; }
<#}#>
    }
}

<# manager.EndBlock(); #>


<#}#>

<#manager.Process(true);#>

这里继续添加ModelAuto类
ModelAuto的后缀名使用ttinclude,这里的后缀名可以随便起,要跟上面的tt文件里引用的一致就行。按照微软的建议:用于include的文件尽量不要使用.tt做后缀名

<#@ 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();
        System.IO.Directory.CreateDirectory(OutputPath+@"\Model");
        foreach(Block block in blocks) {
            String fileName = Path.Combine(OutputPath+@"\Model", 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(0) == fileName) {
                projectItem.Delete();
                return;
            }
        }
    }
}#>

配置好数据库的连接字符串保存后, tt模板就会自动生成实体类了。
在这里插入图片描述

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值