CodeSmith再重温

  很早有个项目Mybatis用了codeS制成模板,当时就是应用,没啥想法、又有一个项目也是CodeSmith做的,模板很复杂,就更无兴致了、也许永远用不到,可是随着生产环境的变化、客户项目的业务不同、略发现挺有意思的:

CodeSmith 8.0:

<%@ CodeTemplate Inherits="CodeTemplate" Language="C#" TargetLanguage="Text" Description="NetTiers main template." Debug="True" ResponseEncoding="UTF-8"%>


<%-- 注册实体层Entity模板 --%>
<%@ Register Name="EntityTemplate" Template="Entity.cst" MergeProperties="Flase" ExcludeProperties=""%>


<%-- 数据库 --%>
<%@ Property Name="SourceDatabase" Type="SchemaExplorer.DatabaseSchema" DeepLoad="True" Optional="False" Category="01. Getting Started - Required" Description="Database that the tables views, and stored procedures should be based on. IMPORTANT!!! If SourceTables and SourceViews are left blank, the Entire Database will then be generated."%>


<%
//创建实体层Entity类
this.GenerateEntityClasses();

Debug.WriteLine("OK");
%>

<script runat="template">
    //生成实体Entity类
private void GenerateEntityClasses()
    {
        CodeTemplate Template =new EntityTemplate();
        foreach(TableSchema table in this.SourceDatabase.Tables)
        {
            string FileDirectory = OutputDirectory +"\"+ table.Name +".cs";
            //生成模板
            Template.SetProperty("Table",table);
            //文件输出
            Template.RenderToFile(FileDirectory,true);
            Debug.WriteLine(FileDirectory +" 创建成功.");
        }
    }
</script>


<script runat="template">
    //解决方案输出路径
private string Directory = String.Empty;
    
    [Editor(typeof(System.Windows.Forms.Design.FolderNameEditor), typeof(System.Drawing.Design.UITypeEditor))] 
    [Optional, NotChecked]
    [DefaultValue("")]
    public string OutputDirectory 
    { 
        get
        {
            return Directory;
        }
        set
        {
            if (value.EndsWith("\")) value = value.Substring(0, value.Length -1);
            Directory = value;
        } 
    }
</script>
View Code
<%@ CodeTemplate Inherits="CodeTemplate" Language="C#" TargetLanguage="Text" Description="NetTiers main template." Debug="True" ResponseEncoding="UTF-8"%>

<%@ Assembly Name="SchemaExplorer"%>
<%@ Import Namespace="SchemaExplorer"%>

<%@ Property Name="Table" Type="TableSchema" DeepLoad="True" Optional="False" Category="01. Getting Started - Required" Description="Database that the tables views, and stored procedures should be based on. IMPORTANT!!! If SourceTables and SourceViews are left blank, the Entire Database will then be generated."%>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Entity
{
    public partial class <%= Table.Name%>
    {
        <%foreach(ColumnSchema col in Table.Columns){ %>
        public <%= col.DataType %> <%= col.Name %> { get ; set ; }
        <% } %>
    }
}
View Code

两段代码,一份是配置文档、一个是模板、用C#语言写,读起来不是很难,目标是根据数据库各个表字段,生成model表。

CodeSmith连接数据库,获取数据库的结构,如各个表的名称,表的字段,表间的关系等等,再根据用户自定义好的模板文件,用数据库结构中的关键字替代模板的动态变量,最终输出并保存为我们需要的目标文件。

原文地址:https://www.cnblogs.com/shiningleo007/p/12603305.html