我的第一个CodeSmith

test.cst:


<%@ CodeTemplate Language="C#" TargetLanguage="Text" Src="" Inherits="" Debug="False" CompilerVersion="v3.5" Description="Template description here." %>
<%-- 加载访问数据库的组件SchemaExplorer,并声明其使用的命名空间 --%>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%-- 数据库 --%>
<%@ Property Name="SourceDatabase" DeepLoad="True" Type="SchemaExplorer.DatabaseSchema" Default="" Optional="False" Category="" Description="" OnChanged="" Editor="" EditorBase="" Serializer="" %>
<%-- 注册实体层Entity模板 --%>
<%@ Register Name="EntityTemplate" Template="Entity.cst" MergeProperties="Flase" ExcludeProperties=""%>
<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>
<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>
<%
//创建实体层Entity类
this.GenerateEntityClasses();

Debug.WriteLine("OK");
%>

 

Entity.cst

 

<%@ CodeTemplate Inherits="CodeTemplate" 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 shouldbe based on. IMPORTANT!!! If SourceTables and SourceViews are left blank, theEntire Database will then be generated." %>
using System;
using System.Collections.Generic;
using System.Text;

 

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

 

你可能感兴趣的:(code)