CodeSmith模板代码生成实战详解

为了提高开发效率,节约开发时间,我们采用了codesmith根据自定义模板,生成代码功能。让单表的增删改查功能从数据访问层到ui展示层一键批量生成。下面就开始codeSmith模板编写。

官网地址:http://www.codesmithtools.com
下载地址:http://www.codesmithtools.com/downloads
我使用的,带破解注册工具的codesmith链接:http://pan.baidu.com/s/1dDdndsd。

傻瓜式安装,不做介绍。只不过你安装完需要很多码。那么烦啦,就用我百度云里面的。带注册软件,安装完之后,不要急于打开codesmith,先去用注册软件注册下。

安装完成,破解成功。

打开codesmith主界面如下。

Note:打开新建Csharp template,然后后缀名为cst的就是模板文件,自己写的模板代码,就在这种后缀格式的文件中。然后光标放在模板文件中,F5即可生成你要代码的文件。

写codesmith模板代码

1、自定义参数模板

Note:从这里我们能看到参数的声明,与基本语法的使用规则,需带<%%>。熟悉之后,在右下角给参数赋值,然后光标放入模板中,点击f5生成代码,看下,推敲下。

2、遍历数据库中表的模板

Note:图片展示的是怎么设置数据库配置

模板代码如下:

<%--引入c#模板--%>
<%@ CodeTemplate Language="C#" TargetLanguage="C#" Debug="False" Description="Create an enum of tables." %>
<%--声明数据库的参数,在左下角的Database属性中,选择要操作的数据库名称--%>
<%@ Property Category="Database" Name="SourceDatabase" Type="SchemaExplorer.DatabaseSchema" Optional="False" Description="Database the table enums will come from." %>
<%--引入下面的类库,操作数据库必备的。不要纠结加入就行啦。--%>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%--SourceDatabase, 是你选择数据库的属性类,涵盖数据库的名称,创建时间,字符串链接,描述等等,自己可以点点看 --%>
public enum <%=SourceDatabase.Name %>Tables
{
<%-- 遍历数据库中的表集合 --%>
<% for(int x = 0; x < SourceDatabase.Tables.Count; x++) 
{ 
    TableSchema table = SourceDatabase.Tables[x];
    if (x < SourceDatabase.Tables.Count -1)
        //输出表名,这里是c#的注释,不会被写进生成的代码中。\t为换行符。
        Response.WriteLine("\t{0},", table.Name);
    else
        Response.WriteLine("\t{0}", table.Name);
}
%>    
}

3、遍历数据库表中的字段,声明并使用自定义函数

<%@ CodeTemplate Language="C#" TargetLanguage="C#" Debug="False" Description="Create a list of properties from database table." %>
<%--声明数据库表的参数,在左下角的表属性中,选择要操作的数据库表--%>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="Context" Description="Table that the object is based on." %>
<%--引入system类型转为c#的数据类型的映射字典 --%>
<%@ Map Name="CSharpAlias" Src="System-CSharpAlias" Description="System to C# Type Map" %>
<%--引入下面的类库,操作数据库必备的。--%>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%--遍历数据库表的字段属性--%>
<% foreach (ColumnSchema column in this.SourceTable.Columns) {  %>
<%--拼接字符串,输出c#中实体的属性--%>
public <%= ControlType(CSharpAlias[column.SystemType.FullName]) %> <%= StringUtil.ToPascalCase(column.Name) %>{ get; set; }

<% } %>
<script runat="template">
 //如果类型为int,或datetime类型输出可空类型
 public string ControlType(object val)
 {
     var ty=val.ToString();
     if(ty=="int")
     {
         return "int?";
     }
     if(ty=="System.DateTime")
     {
         return "System.DateTime?";
     }
     return ty;
 }
</script>

4、批量生成文件,并指定生成文件位置

代码如下:

<%@ Template Language="C#" TargetLanguage="Text" %>
<%-- 注册要生成的模板 --%>
<%@ Register Name="TableEnumTemplate" Template="TableEnum.cst" MergeProperties="Flase" ExcludeProperties=""%>
<%@ Register Name="TableClumTemplate" Template="TableProperties.cst" MergeProperties="Flase" ExcludeProperties=""%>

<%--声明数据库的参数,在左下角的Database属性中,选择要操作的数据库名称--%>
<%@ Property Category="Database" Name="SourceDatabase" Type="SchemaExplorer.DatabaseSchema" Optional="False" Description="Database the table enums will come from." %>
<%--Type数据类型为TableSchema,表明参数Table是一个表对象。--%>
<%@ Property Name="SourceTable" Type="TableSchema" DeepLoad="True" Optional="False" Category="Table" Description="Table Name"%>
<%-- 执行输出文件的函数 --%>
<% this.OutPutFile(); %>
<script runat="template">
    //输出文件
    private void OutPutFile()
    {
        //生成列举表名的模板
        CodeTemplate table =new TableEnumTemplate();
        //指定输出路径
        string tableFilePath = OutputDirectory +"\\"+ this.SourceDatabase.Name +".cs";
        //给子模板参数赋值
        table.SetProperty("SourceDatabase",this.SourceDatabase);
        table.RenderToFile(tableFilePath,true);
        
        //生成列表表字段的模板
        CodeTemplate cloumn =new TableClumTemplate();
        //指定输出路径
        string cloumnFilePath = OutputDirectory +"\\"+ this.SourceTable.Name +".cs";
         //给子模板参数赋值
        cloumn.SetProperty("SourceTable",this.SourceTable);
        cloumn.RenderToFile(cloumnFilePath,true);
    }
    //解决方案输出路径
    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>

数据库表生成md文档模板

<%--目标语言C#--%>
<%@ CodeTemplate Inherits="CodeTemplate" Language="C#" TargetLanguage="Text" Description="" Debug="True" ResponseEncoding="UTF-8"%>
 
<%--Type数据类型为TableSchema,表明参数Table是一个表对象。--%>
<%@ Property Name="Table" Type="TableSchema" DeepLoad="True" Optional="False" Category="Table" Description="Table Name"%>
 
<%--引入数据库操作组件--%>
<%@ Assembly Name="SchemaExplorer"%>
<%@ Import Namespace="SchemaExplorer"%>
### <%=Table.FullName %>表描述
 
|字段名|数据类型|是否可空|数据库类型|长度|描述|
|--|--|--|--|--|--|
<%for(int i=0;i<Table.Columns.Count;i++){%>
|<%=Table.Columns[i].Name.ToString()%>|<%=Table.Columns[i].SystemType.ToString()%>|<%=Table.Columns[i].AllowDBNull?"Yes":"No" %> |<%=Table.Columns[i].NativeType.ToString() %>|<%=Table.Columns[i].Size %>|<%=Table.Columns[i].Description.ToString()%>|
<%}%>       

初始的使用就是这些了,现在我使用的是.net code,使用的是非常多的类库,有了CodeSmith批量生成,10分钟编写好模板,几十个表几分钟就生成了!

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值