CodeSmith使用心得

代码生成器大家都用过吧,CodeSmith我想大家也不陌生。最近就用CodeSmith生成了自己的实体类。当然你也可以用它来生成HTML页面以及文档。

下面我就来说一说我生成实体类的步骤:
一、首先介绍一下CodeSmith 2.6,CodeSmith 2.6安装后,会有3个exe:
1.       CodeSmith.exe即为CodeSmith Explorer,可视化生成代码工具,免费,没有时间限制
2.       CodeSmithConsole.exe 在Command模式下运行,免费,没有时间限制
3.       CodeSmithStudio.exe编辑模板的工具的工具,可以校验模板语法是否正确。试用30天。
CodeSmith模板支持C#、VB.Net语法,可以调用.net类库,语法和.net基本上是一样的。  

二、制作模板
1.在这里我选择了C#作为模板的开发语言。
<%@ CodeTemplate Language="C#" TargetLanguage="Text" Description="Template description here." %> 
2.要生成数据库的实体类,数据连接和表名不可缺少的。在CodeSmith中通过SchemaExplorer.dll来帮你和数据库打交道。
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
在模板中导入SchemaExplorer。
然后设置一系列的需要传入的参数:
<%@ Property Name="DataBase" Type="SchemaExplorer.DatabaseSchema" Category="Context" Description="数据库连接." %>
<%@ Property Name="TableName" Type="System.String" Default="" Optional="False" Category="" Description="表名" %> 

3.CodeSmith模板脚本格式:
<script runat="template"> 
       CodeTemplateRule rule=new CodeTemplateRule();
</script>  

或者:
/// <summary> 
    /// 作用:<%= Description %> 
    /// 作者:<%= Author %> 
    /// 日期:<%= DateTime.Now.ToString() %>
///</summary>  

4.我自己写了一个dll来存放自己的函数 CodeTemplateRule.dll ,其中引用到了SchemaExplorer,举个例子:

public ColumnSchemaCollection GetColumnCollection(DatabaseSchema dataBase,string tableName) 
         
              TableSchemaCollection tables = new TableSchemaCollection(dataBase.Tables); 
              ColumnSchemaCollection columns=null; 
              for(int i=0;i<tables.Count;i++) 
              
                   if(tables[i].Name.ToUpper()==tableName.ToUpper()) 
                   
                        TableSchema ts=tables[i]; 
                        columns=new ColumnSchemaCollection(ts.Columns); 
                   } 
              } 
              return columns; 
         } 

这段代码的含义就是取数据库中某张表所有列的集合。

见Demo文件:
模板文件:entity.cst
自己写的.net程序集:CodeTemplateRule.cs
生成后的代码效果:AccountBookEntity.cs  

三、运行
1.       用CodeSmith.exe运行模板,CodeSmith会弹出对话框来你来填写你的参数。
2.       用CodeSmithConsole.exe运行模板,参数可以放在xml文件中。例如:
<?xml version="1.0" encoding="utf-8" ?>

<codeSmith> 

       <propertySets>

              <propertySet>

                     <property name="SampleStringProperty1">string111111111</property>

                     <property name="SampleBooleanProperty1">false</property>         

              </propertySet>         

       </propertySets>

</codeSmith>

然后用命令执行:

3.       在CodeSmithStudio.exe运行模板  

总结:

代码生成器给我们编程工作带来了很大的便利,不需要做很多重复性的工作。

原文地址:https://www.cnblogs.com/luoyaoquan/p/2080699.html