制作符合平台的CodeSmith代码生产模版

先看生产的结果

///////////////////////////////////////////////////////////////////////////////////////
// File: StandardizationProcess .cs
// Description: Enter summary here after generation.
// ---------------------
// Copyright 谈勇 2015 Our Client
// ---------------------
// History
//    2015/11/26    谈勇    Original Version
///////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MCS.Library.Core;
using MCS.Library.Data.Mapping;
using MCS.Library.Data.DataObjects;
using MCS.Library.SOA.DataObjects;
using MCS.Library.Data;
using MCS.Library.SOA.DataObjects.Workflow;
using MCS.Library.Data.Builder;
using SinoOcean.Seagull2.TransactionData.Implement;
namespace SinoOcean.Seagull2.Framework.MasterData.Implement
{
    /// <summary>
    /// 表示 
    /// </summary>
    [Serializable]
    [XElementSerializable]
    [ORTableMapping("Implement.StandardizationProcess_Acceptance")]
    public class StandardizationProcess
    {
        /// <summary>
        /// 获取或设置 编码
        /// </summary>
        [ORFieldMapping("Code", PrimaryKey = true)]
        [XmlObjectMapping]
        public string Code { get; set; }


        /// <summary>
        /// 获取或设置 标准化工艺编码
        /// </summary>
        [ORFieldMapping("StandardizationProcessCode")]
        [XmlObjectMapping]
        public string StandardizationProcessCode { get; set; }


        /// <summary>
        /// 获取或设置 标准化工艺名称
        /// </summary>
        [ORFieldMapping("StandardizationProcessName")]
        [XmlObjectMapping]
        public string StandardizationProcessName { get; set; }


        /// <summary>
        /// 获取或设置 计划管理时间
        /// </summary>
        [ORFieldMapping("PlanCompleteTime")]
        [XmlObjectMapping]
        public DateTime PlanCompleteTime { get; set; }


        /// <summary>
        /// 获取或设置 实际完成时间
        /// </summary>
        [ORFieldMapping("ActualCompleteTime")]
        [XmlObjectMapping]
        public DateTime ActualCompleteTime { get; set; }


        /// <summary>
        /// 获取或设置 备注
        /// </summary>
        [ORFieldMapping("Remark")]
        [XmlObjectMapping]
        public string Remark { get; set; }


        /// <summary>
        /// 获取或设置 创建时间
        /// </summary>
        [ORFieldMapping("CreateTime")]
        [XmlObjectMapping]
        public DateTime CreateTime { get; set; }


        /// <summary>
        /// 获取或设置 创建人
        /// </summary>
        [ORFieldMapping("Creator")]
        [XmlObjectMapping]
        public string Creator { get; set; }


        /// <summary>
        /// 获取或设置 流程编码
        /// </summary>
        [ORFieldMapping("ResourceID")]
        [XmlObjectMapping]
        public string ResourceID { get; set; }


        /// <summary>
        /// 获取或设置 标段编码
        /// </summary>
        [ORFieldMapping("TendersCode")]
        [XmlObjectMapping]
        public string TendersCode { get; set; }


        /// <summary>
        /// 获取或设置 标段名称
        /// </summary>
        [ORFieldMapping("TendersName")]
        [XmlObjectMapping]
        public string TendersName { get; set; }


    }

    /// <summary>
    /// 表示<see cref="StandardizationProcess"/>的集合
    /// </summary>
    [Serializable]
    public class StandardizationProcessCollection : EditableDataObjectCollectionBase<StandardizationProcess>
    {
    }

    /// <summary>
    /// 表示<see cref="StandardizationProcess"/>的数据适配器
    /// </summary>
    [Serializable]
    public class StandardizationProcessAdapter : UpdatableAndLoadableAdapterBase<StandardizationProcess, StandardizationProcessCollection>
    {
        /// <summary>
        /// 表示<see cref="StandardizationProcessAdapter"/> 的实例,此字段为只读。
        /// </summary>
        public static readonly StandardizationProcessAdapter Instance = new StandardizationProcessAdapter();



        /// <summary>
        /// 载入所有 <see cref="StandardizationProcess"/>/// </summary>
        /// <returns>一个<see cref="StandardizationProcessCollection"/>,包含所查询的对象。</returns>
        public StandardizationProcessCollection LoadAll()
        {
            WhereSqlClauseBuilder where = new WhereSqlClauseBuilder();

            return this.LoadByBuilder(where);
        }

        /// <summary>
        /// 根据 编码 载入 <see cref="StandardizationProcess"/>/// </summary>
        /// <param name="code">编码</param>
        /// <returns>一个<see cref="StandardizationProcess"/><see langword="null"/></returns>
        public StandardizationProcess Load(string code)
        {
            WhereSqlClauseBuilder where = new WhereSqlClauseBuilder();
            where.AppendItem("Code", code);
            return this.LoadByBuilder(where).FirstOrDefault();
        }

        /// <summary>
        /// 根据一组 编码 载入 <see cref="StandardizationProcessCollection"/>/// </summary>
        /// <param name="codes">编码</param>
        /// <returns>一个<see cref="StandardizationProcessCollection"/>,包含所查询的对象。</returns>
        public StandardizationProcessCollection LoadRange(params string[] codes)
        {
            if (codes == null)
                throw new ArgumentNullException("codes");

            if (codes.Length > 0)
            {
                InSqlClauseBuilder inSql = new InSqlClauseBuilder("Code");
                inSql.AppendItem(codes);
                return this.LoadByBuilder(inSql);
            }
            else
            {
                return new StandardizationProcessCollection();
            }
        }

        /// <summary>
        /// 在派生类中重写时,获取数据库连接的配置名称。
        /// </summary>
        protected override string GetConnectionName()
        {
            return DatabaseUtil.TRAN_CONNECTION_STR;
        }
    }

}

 

调用:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SinoOcean.Seagull2.Implement.ModalDialog
{
    public partial class WebFormTest : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            this.Gridview1.DataSource =  SinoOcean.Seagull2.Framework.MasterData.Implement.StandardizationProcessAdapter.Instance.LoadAll();
            this.Gridview1.DataBind();
        }
    }
}

 

显示效果

 

 

CodeSmith 模板代码

<%-- 
Name:平台项目代码生成
Author: 谈勇
Description: 根据指定的数据库表生成访问层类和实体类模板
--%>
<%@ CodeTemplate Language="C#" TargetLanguage="C#" Src="" Inherits="" Debug="True"  Description="sql map" ResponseEncoding="utf-8" %>
<%@ Property Name="ClassBaseTypeName" Type="String" Category="Base Type Name" Default="WorkflowObjectBase" Description="是否要继承此接口" %>

<%@ Property Name="Namespace" Type="System.String" Default="StepByStep.DataObjects" Optional="True" Category="ClassInfo" Description="数据对象的名称空间" %>
<%@ Property Name="DataEntityName" Type="System.String" Default="" Optional="False" Category="ClassInfo" Description="数据实体的类名" %>
<%@ Property Name="DataEntityCollectionName" Type="System.String" Default="" Optional="True" Category="ClassInfo" Description="类名的数据实体集合" %>
<%@ Property Name="DataAdapterName" Type="System.String" Default="" Optional="True" Category="ClassInfo" Description="类名的数据适配器" %>
<%@ Property Name="Loadable" Type="System.Boolean" Default="True" Optional="True" Category="ClassInfo" Description="数据适配器支持加载数据吗?" %>
<%@ Property Name="GenerateLoadByIDS" Type="System.Boolean" Default="True" Optional="True" Category="ClassInfo" Description="数据适配器支持加载数据吗?" %>

<%@ Property Name="ClassName" Type="String" Category="Context" Optional="False" Description="数据对象类名" %>
<%@ Property Name="CollectionClassName" Type="String" Category="Context" Optional="True" Description="数据收集的类名" %>
<%@ Property Name="DB" Type="SchemaExplorer.DatabaseSchema" Category="Context" Description="选择要生产的数据库" %>
<%@ Property Name="TableName" Type="String" Category="Context" Description="设置你要生产的表" %>

<%@ Property Name="DevelopersName" Type="String" Default="谈勇" Category="个人信息设置"  Description="开发人员姓名" %>

<%@ Property Name="GenerateCollection" Type="Boolean" Default="True" Category="输出操作设置" Description="是否生产集合" %>
<%@ Property Name="Xml" Type="Boolean" Default="False"  Category="输出操作设置"  Description="是否与xml关联" %>

<%@ Property Name="ConnectionName" Type="System.String" Default="" Optional="True" Category="Data" Description="Data connection name" %>
<%@ Property Name="ConnectionNameIsExpression" Type="System.Boolean" Default="True" Optional="True" Category="Data" Description="Determin whether Data connection name is an expression" %>
<%@ Property Name="Table" Type="SchemaExplorer.TableSchema" Default="" Optional="False" Category="Data" Description="" OnChanged="" Editor="" EditorBase="" Serializer="" %>

<%@ Assembly Name="SchemaExplorer" %>
<%@ Assembly Name="System.Core" %>
<%@ Assembly Src="CodesmithUtils.cs" %>

<%@ Import Namespace="SchemaExplorer" %>
<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="Codesmith.Common" %>


///////////////////////////////////////////////////////////////////////////////////////
// File: <%=ClassName%> .cs
// Description: Enter summary here after generation.
// ---------------------
// Copyright <%= DevelopersName%> <%= DateTime.Now.Year %> Our Client
// ---------------------
// History
//    <%= DateTime.Now.ToShortDateString() %>    <%= DevelopersName%>    Original Version
///////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MCS.Library.Core;
using MCS.Library.Data.Mapping;
using MCS.Library.Data.DataObjects;
using MCS.Library.SOA.DataObjects;
using MCS.Library.Data;
using MCS.Library.SOA.DataObjects.Workflow;
using MCS.Library.Data.Builder;
<%
SchemaExplorer.ColumnSchema[] pks = GetPrimaryKeys();
%>
namespace <%=Namespace%>
{
    /// <summary>
    /// 表示 <%=DB.Tables[TableName].Description ?? TableName %>
    /// </summary>
    [Serializable]
    [XElementSerializable]
    [ORTableMapping("<%=DB.Tables[TableName].FullName %>")]
    public class <%=ClassName%> <%= string.IsNullOrEmpty(ClassBaseTypeName)?string.Empty : " : " + ClassBaseTypeName  %>
    {
    <% string pkString = ""; %>
    <%foreach(ColumnSchema col in DB.Tables[TableName].Columns){%>
        <%  
            if(col.IsPrimaryKeyMember){
                pkString = ", PrimaryKey = true";    
            }
            else
            {
                pkString ="";
            }
        %>
        <% if(Xml){ %>
        /// <summary>
        /// 获取或设置 <%=col.Description%>
        /// </summary>
        [ORFieldMapping("<%=col.Name%>" <%=pkString%>)]
        [XmlObjectMapping]
        public <%=CSharpUtils.GetCSharpVariableType(col.DataType)%> <%= CSharpUtils.ChangeDbFieldToCSharpProperty(col.Name)%> { get; set;}
        
        <%}else{ %>
        /// <summary>
        /// 获取或设置 <%=col.Description%>
        /// </summary>
        [ORFieldMapping("<%=col.Name%>" <%=pkString%>)]
        public <%=CSharpUtils.GetCSharpVariableType(col.DataType)%> <%= CSharpUtils.ChangeDbFieldToCSharpProperty(col.Name)%> { get; set;}
        <%} %>
        
    <%}%>
    }
    <%if (GenerateCollection) {%>
    
    /// <summary>
    /// 表示<see cref="<%=ClassName%>"/>的集合
    /// </summary>
    [Serializable]
    public class <%=GetCollectionClassName2()%> : EditableDataObjectCollectionBase<<%=ClassName%>>
    {
    }
    <%}%>
    
        /// <summary>
    /// 表示<see cref="<%=DataEntityName %>"/>的数据适配器
    /// </summary>
    public class <%=GetAdapterClassName()%> : <%if (Loadable){%>UpdatableAndLoadableAdapterBase<<%=DataEntityName%>, <%=GetCollectionClassName()%>><%} else {%>UpdatableAdapterBase<<%=DataEntityName%>><%}%>
    {
        /// <summary>
        /// 表示<see cref="<%=GetAdapterClassName()%>"/> 的实例,此字段为只读。
        /// </summary>
        public static readonly <%=GetAdapterClassName()%> Instance = new <%=GetAdapterClassName()%>();

        private <%=GetAdapterClassName()%>()
        {
        }
        
        /// <summary>
        /// 载入所有 <see cref="<%=DataEntityName%>"/>。
        /// </summary>
        /// <returns>一个<see cref="<%=DataEntityCollectionName%>"/>,包含所查询的对象。</returns>
        public <%=DataEntityCollectionName%> LoadAll()
        {
            WhereSqlClauseBuilder where = new WhereSqlClauseBuilder ();
           
            return this.LoadByBuilder(where);
        }

        <%if (GenerateLoadByIDS && pks.Length>0){%>
        /// <summary>
        /// 根据 <%=string.Join(",",GetPrimaryKeysDescriptions()) %> 载入 <see cref="<%=DataEntityName%>"/>。
        /// </summary>
        <%for(int i=0;i<pks.Length;i++){%>
        /// <param name="<%=StringUtil.ToCamelCase(pks[i].Name)%>"><%=pks[i].Description%></param>
        <%}%>
        /// <returns>一个<see cref="<%=DataEntityName%>"/>或<see langword="null"/></returns>
        public <%=DataEntityName %> Load(<%= string.Join(",",GetPrimaryKeysForParameters()) %>)
        {
            WhereSqlClauseBuilder where = new WhereSqlClauseBuilder();
            <%for(int i=0;i<pks.Length;i++){ %>
            where.AppendItem("<%=pks[i].Name%>",<%=StringUtil.ToCamelCase(pks[i].Name)%>);
            <%}%>
            return this.LoadByBuilder(where).FirstOrDefault();
        }
        <%if(pks.Length==1){%>
        
        /// <summary>
        /// 根据一组 <%=pks[0].Description %> 载入 <see cref="<%=DataEntityCollectionName%>"/>。
        /// </summary>
        /// <param name="<%=StringUtil.ToPlural(StringUtil.ToCamelCase(pks[0].Name))%>"><%=pks[0].Description%></param>
        /// <returns>一个<see cref="<%=DataEntityCollectionName%>"/>,包含所查询的对象。</returns>
        public <%=DataEntityCollectionName%> LoadRange(params <%=CSharpUtils.GetCSharpVariableType(pks[0].DataType)%>[] <%=StringUtil.ToPlural(StringUtil.ToCamelCase(pks[0].Name))%>)
        {
            if(<%=StringUtil.ToPlural(StringUtil.ToCamelCase(pks[0].Name))%> == null)
                throw new ArgumentNullException("<%=StringUtil.ToPlural(StringUtil.ToCamelCase(pks[0].Name))%>");
                
            if(<%=StringUtil.ToPlural(StringUtil.ToCamelCase(pks[0].Name))%>.Length>0){
                InSqlClauseBuilder inSql = new InSqlClauseBuilder("<%=pks[0].Name%>");
                inSql.AppendItem(<%=StringUtil.ToPlural(StringUtil.ToCamelCase(pks[0].Name))%>);
                return this.LoadByBuilder(inSql);
            }else{
                return new <%=DataEntityCollectionName%>();
            }
        }
        <%}%>
        <%if(pks.Length>1){
        for(int i=0;i<pks.Length;i++){
        %>
        
        /// <summary>
        /// 根据 <%=pks[i].Description %> 载入 <see cref="<%=DataEntityCollectionName%>"/>。
        /// </summary>
        /// <param name="<%=StringUtil.ToCamelCase(pks[i].Name)%>"><%=pks[i].Description%></param>
        /// <returns>一个<see cref="<%=DataEntityCollectionName%>"/>,包含所查询的对象。</returns>
        public <%=DataEntityCollectionName%> LoadBy<%=StringUtil.ToPascalCase(pks[i].Name)%>(<%=CSharpUtils.GetCSharpVariableType(pks[i].DataType)%> <%=StringUtil.ToCamelCase(pks[i].Name)%>)
        {
            WhereSqlClauseBuilder where = new WhereSqlClauseBuilder ();
            where.AppendItem("<%=pks[i].Name%>",<%=StringUtil.ToCamelCase(pks[i].Name)%>);
            return this.LoadByBuilder(where);
        }
        <%}} //endfor,if%>
        <%}%>
        <%if (GetConnectionName() != null) {%>
        
        /// <summary>
        /// 在派生类中重写时,获取数据库连接的配置名称。
        /// </summary>
        protected override string GetConnectionName()
        {
        <%if(ConnectionNameIsExpression){%>
            return <%=ConnectionName%>;
        <%} else {%>
            return "<%=ConnectionName%>";
        <%}%>
        }
        <%}%>
    }

}

<script runat="template">

    
    public string GetCollectionClassName2()
    {
        string result = CollectionClassName;
        
        if (result == null || result == "")
            result = ClassName + "Collection";
        
        return result;
    }
    
    
    #region adpater
        public string GetConnectionName()
    {
        string result = ConnectionName;
        
        if (result == null || result == "")
            result = null;
        
        return result;
    }
    
    public string GetAdapterClassName()
    {
        string result = DataAdapterName;
        
        if (result == null || result == "")
            result = DataEntityName + "Adapter";
        
        return result;
    }
    
    public string GetCollectionClassName()
    {
        string result = DataEntityCollectionName;
        
        if (result == null || result == "")
            result = DataEntityName + "Collection";
        
        return result;
    }
    
    public SchemaExplorer.ColumnSchema [] GetPrimaryKeys(){
        System.Collections.Generic.List<SchemaExplorer.ColumnSchema> result = new System.Collections.Generic.List<SchemaExplorer.ColumnSchema>();
        foreach(SchemaExplorer.ColumnSchema col in Table.Columns){
            if(col.IsPrimaryKeyMember){
                result.Add(col);
            }
        }
        return result.ToArray();
    }
    
    public string[] GetPrimaryKeysForParameters(){
        System.Collections.Generic.List<string> result = new System.Collections.Generic.List<string>();
        foreach(SchemaExplorer.ColumnSchema col in Table.Columns){
            if(col.IsPrimaryKeyMember){
                result.Add(CSharpUtils.GetCSharpVariableType(col.DataType) + " "  + StringUtil.ToCamelCase(col.Name));
            }
        }
        
        return result.ToArray();
    }
    
    public string[] GetPrimaryKeysDescriptions(){
        System.Collections.Generic.List<string> result = new System.Collections.Generic.List<string>();
        foreach(SchemaExplorer.ColumnSchema col in Table.Columns){
            if(col.IsPrimaryKeyMember){
                result.Add(StringUtil.ToCamelCase(col.Description));
            }
        }
        
        return result.ToArray();
    }
    #endregion
</script>

 

CodeSmith 属性设置

 

模版代码v1.0下载

模版代码v2.0下载

模板代码v3.0下载

 

CodeSmith6.5.0下载地址

 

 

v2.0优化了 CodeSmith属性设置

 

v3.0优化了数据库连接串可以自定义填写

 

posted on 2015-11-26 18:46  广交天下好友  阅读(471)  评论(0编辑  收藏  举报

导航