Codesmith根据模板批量生成代码

codeSimth里面的例子的模板都是一个一个独立开的,通过一个主模板生成方案,要单个生成就用单个模板去生成

第一把要用来生成的子模板注册到主模板中去:

<%@ Register Name="MyEntityClass" Template="C:\MyEntityClass.cst" MergeProperties="False" ExcludeProperties="" %>

Name="MyEntityClass" 模板好像会被注册成一个CodeTemplate的派生类,MyEntityClass会是这个类的名字;

C:\MyEntityClass.cst为你模板的位置,相对位置也可以;

<%@ Register Name="EntityClassTemplate" Template="beingnet.entity.cst" MergeProperties="False" ExcludeProperties="" %>

 

第二为模板添加属性

 当然,我们独立的子模板出会有属性需要设置,这个地方可以利用反射来赋值,代码如下:

CodeTemplate codeTemplate=new MyEntityClassKey();

codeTemplate.SetProperty("IncludeGet", IncludeGet);
codeTemplate.SetProperty("IncludeFind", IncludeFind);
codeTemplate.SetProperty("IncludeSave", IncludeSave);

上面的IncludeGet,IncludeFind就是模板C:\MyEntityClass.cst的一些属性了!后面就是为其设置的值了!

 <%-- 1. Datasource --%>
<%@ Property Name="ChooseSourceDatabase" 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." %>

第三步:输出文件

codeTemplate.RenderToFile("c:/3.txt"true);

后面参数,第一个是输出的地址,第二个是是否覆盖!

<%this.SaveEntityClasses();
%>

<script runat="template">

    private string templateOutputDirectory=@"E:\";
   
 [Editor(typeof(System.Windows.Forms.Design.FolderNameEditor), typeof(System.Drawing.Design.UITypeEditor))]
 [Optional, NotChecked]
 [Category("01. Getting Started - Required")]
 [Description("The directory to output the results to.")]
 [DefaultValue("")]
 public string OutputDirectory
 {
  get
  {
    return templateOutputDirectory;
  }
  set
  {
   if (value.EndsWith("\\")) value = value.Substring(0, value.Length - 1);
   templateOutputDirectory = value;
  }
 }

    private void SaveEntityClasses()
    {
          CodeTemplate entitytemplate = new EntityClassTemplate();
            foreach(TableSchema table in this.ChooseSourceDatabase.Tables)
            {
                  entitytemplate.SetProperty("CurrentTable",table);
                entitytemplate.RenderToFile(this.templateOutputDirectory + "\\"  + table.Name+".cs",true);
             
                Debug.WriteLine(table.Name);
            }
          
    }

</script>

我这发几园子的搜索链接:http://zzk.cnblogs.com/s?w=codesmith 慢慢找自己合适的学习!

 

posted @ 2011-09-04 23:59  园博客  阅读(407)  评论(0)    收藏  举报