浅谈代码生成工具《CodeSmith》的使用(2)

          上篇我们就代码生成工具进行了比较,今天我就CodeSmith的使用系统的进行介绍,并就自己在项目中的写的一套模板共享与大家。首先对工具进行介绍,版本5.0.1.4983,工具如下:
         对CodeSmith是IDE有了简单的了解,下来我们就生成框架实体类进行介绍,以项目模板xb_Model为例介绍:
         一、导入支持语言库:
            <%@ CodeTemplate Language="C#" TargetLanguage="C#"  ResponseEncoding="UTF-8" Description="Generates a very simple business object." %>
        二、导入使用的属性类库:
            命名空间:<%@ Property Name="NameSpace" Type="String" Category="Context" Default="PojectManage" Description="The namespace to use for this class" %>
            数据源表:(不支持视图,如果要使用视图,需要把“SchemaExplorer.TableSchema”换为“SchemaExplorer.ViewSchema”)<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="Context" Description="Table that the object is based on." %>
        三、CodeSmith引用、类库:
              <%@ Assembly Name="SchemaExplorer" %>
              <%@ Assembly Name="System.Data" %>
              <%@ Import Namespace="SchemaExplorer" %>
              <%@ Import Namespace="System.Data" %>
      四、Model层所需的类库:
               using System;(C#中模板的直接拷贝)
      五、代码块:
             namespace <%= NameSpace %>.xb_Model   //<%= NameSpace %>,获取项目的命名空间,可以自定义
            { 
                   /// <summary>
                   ///<%= SourceTable.Name%>数据实体  //SourceTable.Name,获取表的名称
                   /// </summary>
                  [Serializable]
                   public class <%= SourceTable.Name%>
                  {
                        #region 变量定义
                          <% foreach (ColumnSchema column in SourceTable.Columns) { %>
                          <%= GetMemberVariableDeclarationStatement(column) %> //GetMemberVariableDeclarationStatement(column)自定义方法
                          <% } %>
                        CodeSmith代码如下:
                       
Code
 
                       #endregion
                        以上生成代码如下:
                          #region 变量定义
                           private int _com_ID;
                           private int _log_ID;
                           private string _user_ID = String.Empty;
                           private string _nickName = String.Empty;
                           private string _webNet = String.Empty;
                          private string _email = String.Empty;
                          private string _create_Time = String.Empty;
                          private string _commentText = String.Empty;
                          private string _remark = String.Empty;
                          #endregion
                  }
基本的语法和C#差不多。其他的代码模板我共享给大家:/Files/xj0112/xb_Model.rar,如有问题大家一块学习、探讨。
                  
            
posted on 2009-07-27 21:01  维能开发室(吴晓军)  阅读(1467)  评论(4编辑  收藏  举报