Access911.net   |   a9BBS   |   OTaA System  
  搜索文章:  
Access911欢迎您光临  
   主页      上传      繁體版       论坛     
设为首页  |  加入收藏   
  
你现在的位置:文章索引 -> 文章分类 -> ASP/ASP.NET  
 首页|  近日更新|  下载  |  文章索引  |  搜索|  术语|  承接工程|  
 
系统正在加载内容,请耐心等待...
 
 查询
 窗体
 报表
 
 
 VBA
 函数
 ADO/DAO/ADO.NET
 API
 ADP
 安全
 发布
 OA
 ASP/ASP.NET
 其他语言
 控件
 DELPHI
 C#/.Net
 本站
 其他
 小例程
 常用软件
 参考文档
 业主作品
 网友大作
 
 
友情链接
 access911.net
 
访问人次
 1701885
 
站长 E-Mail
 net911@sina.com
 access911@gmail.com
 
RSS 订阅

显示附加信息 >>>

CodeSmith根据SQL数据库表生成非实体类的模板

作者:cg1  摘自:access911.net  :cg1  更新日期:2009-9-5  浏览人次:

 

cg_TableToClass.cst

<%-- 
CodeSmith DBDocumenter Templates
Author:  chenge
--%>
<%@ CodeTemplate Language="C#" TargetLanguage="ASPX" ResponseEncoding="UTF-8" Src="cg_TableToClass_DBDocumenterTemplate.cs" Inherits="cg_TableToClass_DBDocumenterTemplate" Description="Template description here." %>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="DataBinding" Description="选择数据库名及表名。Table that the documentation should be based on." %>
<%@ Property Name="NameSpace" Type="String" Default="pms.shtip.com.cn" Category="Context" Description="默认为名称空间" %>
<%@ Property Name="ClassName" Type="String" Default="" Category="Options" Description="默认为表名" %>
<%@ Property Name="AutoIdToName" Type="Boolean" Default="True" Category="Context" Description="GridPanel中column是否允许编辑" %>
<%@ Property Name="AutoNamePostfix" Type="String" Default="Name" Category="Context" Description="自动根据Id生成Name时的后缀,默认为Name,如:UserId-> UserName" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Assembly Name="System.Design" %>
<%@ Assembly Name="CodeSmith.BaseTemplates" %>
<%@ Assembly Name="CodeSmith.CustomProperties" %>
<%@ Import Namespace="CodeSmith.BaseTemplates" %>
<%@ Import Namespace="CodeSmith.CustomProperties" %>

<%@ Import Namespace="SchemaExplorer" %>

<script runat="template">
    //定义Property属性为选择框的方式是在runat="template"中定义一个enum,然后定义property时定义Type为这个enum即可。
    public enum IdFormatEnum
    {
        Public,
        Protected,
        Internal,
        ProtectedInternal,
        Private
    }
    
    ////将emnu转换为制定字符串
    //public string GetAccessModifier(AccessibilityEnum accessibility)
    //{
    //    switch (accessibility)
    //    {
    //        case AccessibilityEnum.Public: return "public";
    //        case AccessibilityEnum.Protected: return "protected";
    //        case AccessibilityEnum.Internal: return "internal";
    //        case AccessibilityEnum.ProtectedInternal: return "protected internal";
    //        case AccessibilityEnum.Private: return "private";
    //        default: return "public";
    //    }
    //}
    
</script>

namespace <%= NameSpace %>
{
    using System;
    using System.Data.Linq;
    using System.Data.Linq.Mapping;
    using System.Data;
    using System.Collections.Generic;
    using System.Reflection;
    using System.Linq;
    using System.Linq.Expressions;
    using System.ComponentModel;

#region CodeSmith AutoClass <%= SourceTable.FullName %> by <%= System.Environment.MachineName %>.<%= System.Environment.UserName %> <%= System.DateTime.Now.ToString() %>
    /// <summary>
    /// 本类中存放的都是从存储过程调取数据到linq的类。
    /// 操作方法是在sql server中用存储过程生成一个table,然后把这个table
    /// 拖到 dbml 中,获取对应的class并copy到这里。再将存储过程拖到dbml中,
    /// 将生成的内容copy到这里。
    /// 或者用 CodeSmith 模板根据表来生成
    /// </summary>
    public partial class <%= ClassName == "" ? SourceTable.Name : ClassName %>
    {
        <% for (int i = 0; i < SourceTable.Columns.Count; i++) { %>
        private <%= GetDataTypeCSharp(SourceTable.Columns[i]) %> _<%= SourceTable.Columns[i].Name %>;     //<%=SourceTable.Columns[i].NativeType%>:<%=SourceTable.Columns[i].Size%> <%=SourceTable.Columns[i].Description%>
            <% 
            string fieldName = SourceTable.Columns[i].Name;
            string fieldNewName ="";
            
            if ((AutoIdToName) && (fieldName.Length>2)) {
                if (fieldName.Substring(fieldName.Length-2,2)=="Id"){
                fieldNewName = fieldName.Substring(0,fieldName.Length-2) + AutoNamePostfix;
        %>
        private string _<%= fieldNewName %>;  //auto id to name<% }} %>
        <% } %>     
        <% for (int i = 0; i < SourceTable.Columns.Count; i++) { %>
        // <%=SourceTable.Columns[i].Name%>        <%=SourceTable.Columns[i].DataType%>(<%=SourceTable.Columns[i].Size%>)        <%=SourceTable.Columns[i].Description%>
        public <%= GetDataTypeCSharp(SourceTable.Columns[i]) %> <%= SourceTable.Columns[i].Name %>
        {   
            get{return this._<%= SourceTable.Columns[i].Name %>;}
            set{if ((this._<%= SourceTable.Columns[i].Name %> != value)){this._<%= SourceTable.Columns[i].Name %> = value;}}
        }
            <% 
            string fieldName = SourceTable.Columns[i].Name;
            string fieldNewName ="";
            
            if ((AutoIdToName) && (fieldName.Length>2)) {
                if (fieldName.Substring(fieldName.Length-2,2)=="Id"){
                fieldNewName = fieldName.Substring(0,fieldName.Length-2) + AutoNamePostfix;
        %>//根据AutoIdToName 自动在 ...Id 后面加 ...Name
        public string <%= fieldNewName %>
        {   
            get{return this._<%= fieldNewName %>;}
            set{if ((this._<%= fieldNewName %> != value)){this._<%= fieldNewName %> = value;}}
        }   <%
                }   //end of if ((AutoIdToName) && (fieldName.Length>2)
            }      //endi of if (fieldName.Substring(fieldName.Length-2,2)=="Id")
            %>
        <% } %>        

    }
#endregion
}



cg_TableToClass_DBDocumenterTemplate.cs

using System;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.ComponentModel;
using System.ComponentModel.Design;
using CodeSmith.Engine;
using SchemaExplorer;


public class cg_TableToClass_DBDocumenterTemplate : CodeTemplate
{
    // Number of columns that should be displayed on the summary lists.
    public const int NUM_OF_COLUMNS = 3;
    
    private string _outputDirectory = String.Empty;
    

      
    [Editor(typeof(System.Windows.Forms.Design.FolderNameEditor), typeof(System.Drawing.Design.UITypeEditor))] 
    [Optional]
    [Category("Output")]
    [Description("The directory to output the results to.")]
    public string OutputDirectory 
    {
        get
        {
            // default to the directory that the template is located in
            if (_outputDirectory.Length == 0) return this.CodeTemplateInfo.DirectoryName + "output\\";
            
            return _outputDirectory;
        }
        set
        {
            if (!value.EndsWith("\\")) value += "\\";
            _outputDirectory = value;
        } 
    }
    
    //获取主键字段,如果有多个字段则用英文逗号分隔
    public string GetPrimaryKeyColumns(SchemaExplorer.MemberColumnSchemaCollection columns){
        string columnName ="" ;
        if (columns.Count>0){
            foreach(SchemaExplorer.ColumnSchema c in columns){
                columnName+=c.Name+",";
            }
            if ((columnName.Length>0) && (columnName.Substring(columnName.Length-1,1)==",")){
                columnName=columnName.Substring(0,columnName.Length-1);
            }
            return columnName;
        }else{
            return "";
            }
            
    }
    
    //根据选定的表获取所有的字段名
    public string GetFieldList(SchemaExplorer.TableSchema sourceTable){
        //System.Diagnostics.Debug.Print("{0}",sourceTable.ToString());
        string columnName ="" ;
        if (sourceTable.Columns.Count>0){
            foreach(SchemaExplorer.ColumnSchema c in sourceTable.Columns){
                columnName+=c.Name+",";
            }
            if ((columnName.Length>0) && (columnName.Substring(columnName.Length-1,1)==",")){
                columnName=columnName.Substring(0,columnName.Length-1);
            }
            return columnName;
        }else{
            return "";
            }
     
        
        
    }
    
    //将.net的数据类型转换为ext的数据类型。
    public string GetDataType(string typeName){
        //return typeName;
        switch (typeName)
        {
            case "nvarchar":
            case "char":
                return "String";
                break;
            case "int":
                return "Int";
                break;
            case "datetime":
                return "Date";
                break;
            case "bit":
                return "Boolean";
                break;
            case "numeric":
                return "Float";
                break;
            default:
                return("U-" + typeName);
        }
        
    }
    
    public string GetDataTypeCSharp(SchemaExplorer.ColumnSchema column){
        //return typeName;
        string result="";
        switch (column.NativeType)
        {
            case "text":
            case "varchar":
            case "nvarchar":
            case "char":
                result="String";
                break;
            case "int":
                result = column.AllowDBNull!=true ? "Int" : "System.Nullable<Int>" ;
                break;
            case "datetime":
                result = column.AllowDBNull!=true ? "System.DateTime" : "System.Nullable<System.DateTime>" ;
                break;
            case "bit":
                result= "bool";
                break;
            case "numeric":
                result= column.AllowDBNull!=true ? "decimal" : "System.Nullable<decimal>";
                break;
            default:
                result = "U-" + column.NativeType;
                break;
        }
        return result;
        
    }
    
    public string GetDataTypeCSharp(string typeName){
        //return typeName;
        switch (typeName)
        {
            case "nvarchar":
            case "char":
                return "String";
                break;
            case "int":
                return "Int";
                break;
            case "datetime":
                return "Date";
                break;
            case "bit":
                return "Boolean";
                break;
            case "numeric":
                return "Float";
                break;
            default:
                return("U-" + typeName);
        }
        
    }    
    public void OutputTemplate(CodeTemplate template)
    {
        this.CopyPropertiesTo(template);
        template.Render(this.Response);
    }
    
    public SqlDataReader GetSystemInformation(string connectionString)
    {
        SqlConnection cn = new SqlConnection(connectionString);
        SqlCommand cmd = new SqlCommand();
        
        cmd.Connection = cn;
        cmd.CommandText = "master.dbo.xp_msver";
        cmd.CommandType = CommandType.StoredProcedure;
        
        cn.Open();
        SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
        
        return reader;
    }
    
    public void OutputExceptionInformation(Exception exception, int indentLevel)
    {
        int originalIndentLevel = Response.IndentLevel;
        Response.IndentLevel = indentLevel;
        Response.WriteLine("<table width=\"95%\">");
        Response.WriteLine("<tr>");
        Response.WriteLine("    <td>");
        Response.WriteLine("        <span class=\"exceptionText\">");
        Response.WriteLine("        An exception occurred while attempting to execute the template:" );
        Response.WriteLine("        " + exception.Message);
        Response.WriteLine("        </span>");
        Response.WriteLine("    </td>");
        Response.WriteLine("</tr>");
        Response.WriteLine("</table>");
        Response.IndentLevel = originalIndentLevel;
    }
    
    public void OutputSystemInformation(string connectionString, int indentLevel)
    {
        SqlDataReader info = null;
        
        try
        {
            info = this.GetSystemInformation(connectionString);
            
            int originalIndentLevel = Response.IndentLevel;
            Response.IndentLevel = indentLevel;
            Response.WriteLine("<table width=\"95%\">");
            
            while (info.Read())
            {
                Response.WriteLine("<tr>");
                Response.WriteLine("    <td width=\"40\"> </td>");
                Response.WriteLine("    <td width=\"100\">");
                Response.WriteLine("        <b><span class=\"bodyText\">" + info["Name"] + ":</span></b>");
                Response.WriteLine("    </td>");
                Response.WriteLine("    <td width=\"100%\" align=\"left\">");
                Response.WriteLine("        <span class=\"bodyText\">" + info["Character_Value"].ToString().Trim() + "</span>");
                Response.WriteLine("    </td>");
                Response.WriteLine("</tr>");
            }
            
            Response.WriteLine("</table>");
            Response.IndentLevel = originalIndentLevel;
        }
        catch (Exception ex)
        {
            this.OutputExceptionInformation(ex, indentLevel);
        }
        finally
        {
            if (info != null) info.Close();
        }
    }
    
    public string GetParameterSize(ParameterSchema parameter)
    {
        string parameterSize = parameter.Size.ToString();
        
        if (parameter.NativeType == "numeric" && parameter.Precision != 0)
        {
            parameterSize += "(" + parameter.Precision.ToString() + "," + parameter.Scale + ")";
        }
        
        return parameterSize;
    }
    
    public string GetColumnSize(ColumnSchema column)
    {
        string columnSize = column.Size.ToString();
        
        if (column.NativeType == "numeric" && column.Precision != 0)
        {
            columnSize += "(" + column.Precision.ToString() + "," + column.Scale + ")";
        }
        
        return columnSize;
    }
    
    public string GetColumnSize(ViewColumnSchema column)
    {
        string columnSize = column.Size.ToString();
        
        if (column.NativeType == "numeric" && column.Precision != 0)
        {
            columnSize += "(" + column.Precision.ToString() + "," + column.Scale + ")";
        }
        
        return columnSize;
    }
    
    public void DeleteFiles(string directory, string searchPattern)
    {
        string[] files = Directory.GetFiles(directory, searchPattern);
        
        for (int i = 0; i < files.Length; i++)
        {
            try
            {
                File.Delete(files[i]);
            }
            catch (Exception ex)
            {
                Response.WriteLine("Error while attempting to delete file (" + files[i] + ").\r\n" + ex.Message);
            }
        }
    }
}


生成的结果如下:

namespace pms.shtip.com.cn
{
    using System;
    using System.Data.Linq;
    using System.Data.Linq.Mapping;
    using System.Data;
    using System.Collections.Generic;
    using System.Reflection;
    using System.Linq;
    using System.Linq.Expressions;
    using System.ComponentModel;

#region CodeSmith AutoClass dbo.ENBasicAttrubite by PY-CHENGE1.Administrator 2009-9-5 10:56:43
    /// <summary>
    /// 本类中存放的都是从存储过程调取数据到linq的类。
    /// 操作方法是在sql server中用存储过程生成一个table,然后把这个table
    /// 拖到 dbml 中,获取对应的class并copy到这里。再将存储过程拖到dbml中,
    /// 将生成的内容copy到这里。
    /// 或者用 CodeSmith 模板根据表来生成
    /// </summary>
    public partial class ClassTable
    {
        private Int _Id;     //int:4 公司基本信息ID

        private String _IdentityCard;     //nvarchar:25 身份证

        private String _RealName;     //nvarchar:25 姓名

        private String _WorkId;     //nvarchar:20 工号

        private System.Nullable<Int> _Gender;     //int:4 性别

        private System.Nullable<Int> _HouseholdId;     //int:4 户籍

        private System.Nullable<System.DateTime> _Birthday;     //datetime:8 出生日期

        private String _Telphone;     //nvarchar:50 固定电话

        private String _Mobile;     //nvarchar:50 手机电话

        private String _HouseholdAddress;     //nvarchar:150 户籍地址

        private String _CurrentAddress;     //nvarchar:150 现住地址

        private System.Nullable<Int> _EducationId;     //int:4 最高学历

        private String _LastGraduateAcademy;     //nvarchar:70 最后毕业院校

        private System.Nullable<System.DateTime> _AddDate;     //datetime:8 添加日期

        private System.Nullable<Int> _AddUserId;     //int:4 添加人的编号

        private System.Nullable<System.DateTime> _LastModifyDate;     //datetime:8 最后修改日期

        private System.Nullable<Int> _LastModifyUserId;     //int:4 最后修改人id

        private String _Photo;     //nvarchar:150 照片

        private String _FeedBack;     //nvarchar:500 备注

        private System.Nullable<Int> _IsDel;     //int:4 0为正常 1为删除

        // Id        Int32(4)        公司基本信息ID
        public Int Id
        {   
            get{return this._Id;}
            set{if ((this._Id != value)){this._Id = value;}}
        }
            
        // IdentityCard        String(25)        身份证
        public String IdentityCard
        {   
            get{return this._IdentityCard;}
            set{if ((this._IdentityCard != value)){this._IdentityCard = value;}}
        }
            
        // RealName        String(25)        姓名
        public String RealName
        {   
            get{return this._RealName;}
            set{if ((this._RealName != value)){this._RealName = value;}}
        }
            
        // WorkId        String(20)        工号
        public String WorkId
        {   
            get{return this._WorkId;}
            set{if ((this._WorkId != value)){this._WorkId = value;}}
        }
            
        // Gender        Int32(4)        性别
        public System.Nullable<Int> Gender
        {   
            get{return this._Gender;}
            set{if ((this._Gender != value)){this._Gender = value;}}
        }
            
        // HouseholdId        Int32(4)        户籍
        public System.Nullable<Int> HouseholdId
        {   
            get{return this._HouseholdId;}
            set{if ((this._HouseholdId != value)){this._HouseholdId = value;}}
        }
            
        // Birthday        DateTime(8)        出生日期
        public System.Nullable<System.DateTime> Birthday
        {   
            get{return this._Birthday;}
            set{if ((this._Birthday != value)){this._Birthday = value;}}
        }
            
        // Telphone        String(50)        固定电话
        public String Telphone
        {   
            get{return this._Telphone;}
            set{if ((this._Telphone != value)){this._Telphone = value;}}
        }
            
        // Mobile        String(50)        手机电话
        public String Mobile
        {   
            get{return this._Mobile;}
            set{if ((this._Mobile != value)){this._Mobile = value;}}
        }
            
        // HouseholdAddress        String(150)        户籍地址
        public String HouseholdAddress
        {   
            get{return this._HouseholdAddress;}
            set{if ((this._HouseholdAddress != value)){this._HouseholdAddress = value;}}
        }
            
        // CurrentAddress        String(150)        现住地址
        public String CurrentAddress
        {   
            get{return this._CurrentAddress;}
            set{if ((this._CurrentAddress != value)){this._CurrentAddress = value;}}
        }
            
        // EducationId        Int32(4)        最高学历
        public System.Nullable<Int> EducationId
        {   
            get{return this._EducationId;}
            set{if ((this._EducationId != value)){this._EducationId = value;}}
        }
            
        // LastGraduateAcademy        String(70)        最后毕业院校
        public String LastGraduateAcademy
        {   
            get{return this._LastGraduateAcademy;}
            set{if ((this._LastGraduateAcademy != value)){this._LastGraduateAcademy = value;}}
        }
            
        // AddDate        DateTime(8)        添加日期
        public System.Nullable<System.DateTime> AddDate
        {   
            get{return this._AddDate;}
            set{if ((this._AddDate != value)){this._AddDate = value;}}
        }
            
        // AddUserId        Int32(4)        添加人的编号
        public System.Nullable<Int> AddUserId
        {   
            get{return this._AddUserId;}
            set{if ((this._AddUserId != value)){this._AddUserId = value;}}
        }
            
        // LastModifyDate        DateTime(8)        最后修改日期
        public System.Nullable<System.DateTime> LastModifyDate
        {   
            get{return this._LastModifyDate;}
            set{if ((this._LastModifyDate != value)){this._LastModifyDate = value;}}
        }
            
        // LastModifyUserId        Int32(4)        最后修改人id
        public System.Nullable<Int> LastModifyUserId
        {   
            get{return this._LastModifyUserId;}
            set{if ((this._LastModifyUserId != value)){this._LastModifyUserId = value;}}
        }
            
        // Photo        String(150)        照片
        public String Photo
        {   
            get{return this._Photo;}
            set{if ((this._Photo != value)){this._Photo = value;}}
        }
            
        // FeedBack        String(500)        备注
        public String FeedBack
        {   
            get{return this._FeedBack;}
            set{if ((this._FeedBack != value)){this._FeedBack = value;}}
        }
            
        // IsDel        Int32(4)        0为正常 1为删除
        public System.Nullable<Int> IsDel
        {   
            get{return this._IsDel;}
            set{if ((this._IsDel != value)){this._IsDel = value;}}
        }
            

    }
#endregion
}



参考:
http://www.accdb.net/default.asp?tag=CodeSmith

上述文章只代表作者的学习经历,并非绝对正确,仅供参考!

本站文章旨在为该问题提供解决思路及关键性代码,并不能完成应该由网友自己完成的所有工作,请网友在仔细看文章并理解思路的基础上举一反三、灵活运用。

access911.net 原创文章,作者本人对文章保留一切权利。
如需转载必须征得作者同意并注明本站链接

 

 
相关文章
     没有手动相关文章
 
评论
     查看或发表更多的评论,请单击这里。
 
 
 
 
 
   
  Access911.net   |   a9BBS   |   OTaA System   |
建站日期:2000年4月2日  |  设计施工:陈格 ( access911 & cg1 )
 Copyright © 2000 - 2003 COMET, 陈格 保留所有权利