首页 > 代码库 > CodeSmith单表生成实体模板

CodeSmith单表生成实体模板

 

<%@ Template Language="C#" TargetLanguage="C#" %>
<%@ Assembly Name="SchemaExplorer"%>
<%@ Import Namespace="SchemaExplorer"%>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema"%>

using System;
using System.Collections.Generic;
namespace Model
{
    public class <%=GetClassName()%>Entity
    {
    <%foreach(ColumnSchema column in this.SourceTable.Columns)%>
    <%{%>   
        /// <summary>        
        ///<%=column.Description%>
        /// </summary>
        public <%=GetCSDataType(column)%> <%=ToPascal(column.Name)%>{get;set;}
    <%}%>
    }
}

<script runat="template">
    //Pascal命名法(将首字母大写)
    public string ToPascal(string s)
    {
        return s.Substring(0,1).ToUpper()+s.Substring(1);
    }
    //骆驼命名法(将首字母小写)
    public string ToCamel(string s)
    {
        return s.Substring(0,1).ToLower()+s.Substring(1);
    }
    //得到类的名字(由表名而来)
    public string GetClassName()
    {
        string s=this.SourceTable.Name;//取到表名
        //判断表名是不是以S结尾,如果是去掉S
        if (s.EndsWith("s"))
        {
             return ToPascal(s.Substring(0,s.Length-1));
        }
        return ToPascal(s);
    }
    //得到C#的数据类型(将基本常用的数据类型意逐个转换)
    public static string GetCSDataType(ColumnSchema column)
    {
        if (column.Name.EndsWith("TypeCode")) return column.Name;
        switch (column.DataType)
        {
            case DbType.AnsiString: return "string";
            case DbType.AnsiStringFixedLength: return "string";
            case DbType.Binary: return "byte[]";
            case DbType.Boolean: return "bool";
            case DbType.Byte: return "byte";
            case DbType.Currency: return "decimal";
            case DbType.Date: return "DateTime";
            case DbType.DateTime: return "DateTime";
            case DbType.Decimal: return "decimal";
            case DbType.Double: return "double";
            case DbType.Guid: return "Guid";
            case DbType.Int16: return "short";
            case DbType.Int32: return "int";
            case DbType.Int64: return "long";
            case DbType.Object: return "object";
            case DbType.SByte: return "sbyte";
            case DbType.Single: return "float";
            case DbType.String: return "string";
            case DbType.StringFixedLength: return "string";
            case DbType.Time: return "TimeSpan";
            case DbType.UInt16: return "ushort";
            case DbType.UInt32: return "uint";
            case DbType.UInt64: return "ulong";
            case DbType.VarNumeric: return "decimal";
            default:
            {
                return "__UNKNOWN__" + column.NativeType;
            }
        }
    }
    public override string GetFileName()
    {
        return this.GetClassName()+".cs";
    }
</script>

 

CodeSmith单表生成实体模板