31
2016
08

.Net框架搭建之辅助模版代码生成工具


在.Net框架搭建讲解中,提到了代码自动生成来减少开发人员人工作量,比如数据库对应的Model、最基层的Repository类和接口等等,除了类名不一样,其他都一样,没必要再手写一遍。 

我在这里,介绍使用CodeSmith模版生成Model类,其他的都一样,拿到表名和各字段名、字段类型等等,想怎么生成就能怎么生成。


首先,在硬盘中,建立一个文件夹,用来放模版文件,比如: 

F:\pukuimin\InjectExample\ExampleCodeSmithTemplate 

点击添加文件夹位置,把这个文件夹加到CodeSmith管理器 

好了之后,就可以新建模版文件了,在刚加的文件夹上右键,新建CS类型模版文件。 

重命名为 Model.cst 

内容:

<%-- 
Name:
Author: pukuimin
Description: 
--%>
<%@ Template Language="C#" TargetLanguage="C#" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Import Namespace="System.Globalization" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Map Name="CSharpAlias" Src="System-CSharpAlias" Description="数据库字段类型与C#类型的映射表" %>
<%-- 要打印的表 --%>
<%@ Property Name="Table"  Type="SchemaExplorer.TableSchema" DeepLoad="True" Optional="False" Category="需要的数据表" Description="table ." %>
<% 
string TableName=Table.Name;
/*
for(int i=TableName.Length-1;i>=0;i--)
{
    if(TableName[i]>='A'&& TableName[i]<='Z')
    {
        TableName=TableName.Substring(0,i)+TableName.Substring(i,1).ToLower()+TableName.Substring(i+1);
        break;
    }
}
*/
string primaryname=Table.PrimaryKey.MemberColumns[0].Name;
string primarytype= CSharpAlias[Table.PrimaryKey.MemberColumns[0].SystemType.FullName];
string autoname="",autotype="";
 foreach(ColumnSchema cs in Table.Columns) 
 {  
     if( ((bool)cs.ExtendedProperties["CS_IsIdentity"].Value) == true)
     {
        autoname=cs.Name;
        autotype=CSharpAlias[cs.SystemType.FullName];
         break;
     }
 }
List<string> fkeys=new List<string>();//存储外键列及对应的主键表名
foreach(var item in Table.ForeignKeys)
{
    fkeys.Add(item.ForeignKeyMemberColumns[0].Name);
    //Response.Write(item.ForeignKeyMemberColumns[0].Name+"--"+item.PrimaryKey.Table.Name+"\n"); 
}
%>
/* ==============================================================================
 * 功能描述:SysUserInfo  
 * 创 建 者:蒲奎民
 * 创建日期:2016-08-29 15:58:13
 * CLR Version :4.0.30319.42000
 * ==============================================================================*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InjectExample.Model
{
    public partial class <%=Table.Name%>
    {
             <% for(int i=0;i<Table.Columns.Count;i++) {
             ColumnSchema col=Table.Columns[i];
             string temptype=CSharpAlias[col.SystemType.FullName];             
              %>
        /// <summary>
        /// <%=col.Description==""?col.Name:col.Description %>
        /// </summary>
        public <%=temptype+(col.AllowDBNull&&temptype!="string"?"?":"")%> <%=col.Name%> { get; set; }
                <%
                }
                %>
    }
}


保存,然后,点击工具栏的Build Template,生成一下。 

右下角会有选择数据库表,我们就需要添加数据库。 

添加数据库,再选择库中的一张表。 

选择好了之后,点击工具栏的 Generate 生成model内容了。 

生成的内容: 

这个代码就能直接使用了,如果不能用,要自己改改模版。


其他模版不一一介绍,大家可以参考此模版改造。


再加一个,把模版生成的代码直接保存到文件的CS模版。 

模版内容:

<%-- 
Name:GenerateFiles.cst
Author: pukuimin
Description: 生成并输出cs文件的模版
--%>
<%@ Template Language="C#" TargetLanguage="Text" Inherits="CodeTemplate" Encoding="utf-8"%>
<%@ Assembly Name="SchemaExplorer"%>
<%@ Import Namespace="SchemaExplorer"%>
<%-- 数据库 --%>
<%@ Property Name="SourceDatabase"  Type="SchemaExplorer.DatabaseSchema" DeepLoad="True" Optional="False" Category="需要的数据库" Description="Database"%>
<%-- 注册实体层Model模板 --%>
<%@ Register Name="ModelTemplate" Template="Model.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;
        } 
    }
    public string GetSubspace(string tableName)
    {
        for(int i=tableName.Length-1;i>=0;i--)
        {
            if(tableName[i]>='A'&& tableName[i]<='Z')
            {
                tableName=tableName.Substring(0,i)+tableName.Substring(i,1).ToLower()+tableName.Substring(i+1);
                break;
            }
        }
        return tableName;
    }
        //生成实体Entity类
    private void GenerateEntityClasses()
    {
        CodeTemplate modelTemplate =new ModelTemplate();
        foreach(TableSchema table in this.SourceDatabase.Tables)
        {
            string TableName=table.Name;
            string subspace=GetSubspace(TableName);
            if(TableName!="") continue;//可以指定只生成一个表,不等于这个表名就跳过生成,为空就生成所有表
            //#error 上面行修改成要生成的表名(修改后可注释本行)
            Response.WriteLine("……………………"+TableName +" 开始生成……………………");
            string modelDirectory = OutputDirectory +"\\InjectExample.Model\\"+TableName+".cs";
            //生成Model.cs模板文件
            modelTemplate.SetProperty("Table",table);
            modelTemplate.RenderToFile(modelDirectory,true);//文件输出
            Response.WriteLine(modelDirectory +" 创建成功.");
            Response.WriteLine("……………………"+TableName +" 完成生成……………………");
        }
    }
</script>
<%
    //创建实体层Entity类
    this.GenerateEntityClasses();
    Debug.WriteLine("全部生成完成!");
    Response.WriteLine("全部生成完成!");
%>


点击生成之后,在你选择的目录下,就直接生成了Model.cs文件,连创建新文件都省了。



版权声明:
作者:真爱无限 出处:http://www.pukuimin.top 本文为博主原创文章版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接.
« 上一篇下一篇 »

相关文章:

评论列表:

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。