CodeSmith 生成实体类 模板

不完全是原创,抄抄改改之后的结果,可以当做研究学习之用,幻影拍砖。

<%@ CodeTemplate Language="C#" TargetLanguage="Text" Src="" Inherits=""
    Debug="False" LinePragmas="True" Description="" %>

<%@ Assembly Name="SchemaExplorer" %>

<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="SchemaExplorer" %>

<%@ Property Name="ClassName" Type="System.String" Default="Class1" Optional="False" Category="" Description="" OnChanged="" Editor="" EditorBase="" Serializer="" %>
<%@ Property Name="NameSpace" Type="System.String" Default="Class1" Optional="False" Category="" Description="" OnChanged="" Editor="" EditorBase="" Serializer="" %>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Optional="True" Category="" Description="" OnChanged="" Editor="" EditorBase="" Serializer="" %>

<Script runat="Template">
protected string SqlTypeToCSharp(ColumnSchema column)
{
    string type = string.Empty;
    switch(column.DataType)
    {
        case System.Data.DbType.Single:
            type=column.AllowDBNull?"float?":"float";
            break;
        case System.Data.DbType.Xml:
            type="string";
            break;
        case System.Data.DbType.Boolean:
            type=column.AllowDBNull?"bool?":"bool";
            break;
        case System.Data.DbType.Guid:
            type="Guid";
            break;
        case System.Data.DbType.Object:
            type="object";
            break;
        default:
            type=column.AllowDBNull?column.SystemType.ToString() + "?":column.SystemType.ToString();
            break;
    }
    type = type.Replace("System.","");
    if(type.IndexOf("Byte[]")>=0 || type.IndexOf("String")>=0)
    {
        type = type.Replace("?","");
    }
    if(type.IndexOf("DateTime")==-1 && type.IndexOf("Int")==-1
        && type.IndexOf("Guid")==-1)
    {
        type = type.ToLower();
    }
  return type;
}
</Script>

<Script runat="Template">
protected string GetSqlColumnType(ColumnSchema column)
{
       string param =column.NativeType;
       switch (column.DataType)
       {
             case DbType.Decimal:
             {
                   param += "(" + column.Precision + ", " + column.Scale + ")";
                   break;
             }
             default:
             {
                   if (column.Size > 0)
                    {
                        param += "(" + column.Size + ")";
                       }
                   break;
             }
       }
       return param;
}
</Script>

<Script runat="Template">
protected string UpperFirstChar(string value)
{
  string upper = string.Empty;
  if (string.IsNullOrEmpty(value) || value.Trim().Length == 0)
  {
      return value;
  }
  upper = value.Substring(0, 1).ToUpper();
  if (value.Length < 2)
  {
      return upper;
  }
  return upper + value.Substring(1, value.Length-1);
}

protected string LowerFirstChar(string value)
{
    string lower = string.Empty;
    if (string.IsNullOrEmpty(value) || value.Trim().Length == 0)
    {
        return value;
    }
    lower = value.Substring(0, 1).ToLower();
    if (value.Length < 2)
    {
        return lower;
    }
    return lower + value.Substring(1, value.Length-1);
}
</Script>

<Script runat="Template">
private string GetDefault(ColumnSchema column)
{
    string value = column.ExtendedProperties["CS_Default"].Value.ToString().Replace("(","").Replace(")","");
    if(string.IsNullOrEmpty(value))
    {
        return "";
    }
    string type=SqlTypeToCSharp(column).ToLower();
    if(type.IndexOf("byte[]")>=0 || type.IndexOf("object")>=0)
    {
        return "";
    }
    if(type.IndexOf("guid")>=0)
    {
        value="new Guid(\""+ value +"\")";
    }
    else if(type.IndexOf("datetime")>=0)
    {
        int day=0;
        if(int.TryParse(value,out day))
        {
            value="new DateTime(1900,1,1).AddDays("+ day +")";
        }
        else
        {
            value="DateTime.Parse(\""+ value +"\")";
        }
    }
    else
    {
        int start=value.IndexOf("'");
        int end=value.LastIndexOf("'");
        if(start>=0 && end>=0 && start<=end)
        {
            value=value.Substring(start+1,end-1-start);
        }
        if(type.IndexOf("bool")>=0)
        {
            value=(value=="1"?"true":"false");
        }
        else if(type.IndexOf("string")>=0)
        {
            value="\""+value+"\"";
        }
        else if(type.IndexOf("decimal")>=0)
        {
            value=value+"M";
        }
    }
    return value;
}

protected bool HasDefault(ColumnSchema column)
{
    return !string.IsNullOrEmpty(GetDefault(column));
}
</Script>
using System;
using System.Data;
using System.Collections.Generic;

namespace <%=NameSpace %>
{
    /// <summary>
    /// Table <%= SourceTable.Name %> Entity
    /// Author: CodeSmith
    /// Created Date: <%= DateTime.Now.ToShortDateString()%>
    /// </summary>
    [Serializable()]
    public class <%=ClassName %>
    {
        #region private fileds
    <%for(int i=0;i<SourceTable.Columns.Count;i++) {%>
        //<%=GetSqlColumnType(SourceTable.Columns[i])%>
        private <%=SqlTypeToCSharp(SourceTable.Columns[i])%> <%= "_" + LowerFirstChar(SourceTable.Columns[i].Name)%> <%if(HasDefault(SourceTable.Columns[i])){%>=<%=GetDefault(SourceTable.Columns[i])%><%}%>;
    <%}%>
        #endregion
        #region public property
    <%for(int i=0;i<SourceTable.Columns.Count;i++) {%>
        /// <summary>
        /// <%=SourceTable.Columns[i].Description%>
        /// </summary>
        /// <returns></returns>
        public <%=SqlTypeToCSharp(SourceTable.Columns[i])%> <%=UpperFirstChar(SourceTable.Columns[i].Name)%>
        {
            get { return <%="_" + LowerFirstChar(SourceTable.Columns[i].Name)%>;}
            set { <%="_" + LowerFirstChar(SourceTable.Columns[i].Name)%>=value;}
        }
    <%}%>
        #endregion
    }
}

原文地址:https://www.cnblogs.com/gaotianle/p/1733739.html