为PetaPoco添加实体模板

Brad为我们提供了T4模板,因为公司一直在使用CodeSmith,故为其写了一个CodeSmith的模板,代码如下:

<%-- 
Name:EntityTemplates
Author:Qi Fei 
Description:Generate a entity file in C#
--%>

<%@ CodeTemplate Language="C#" TargetLanguage="Text" Src="" Inherits="" Debug="False" Description="" ResponseEncoding="UTF-8" %>
<%@ Property Name="Namespace" Type="System.String" Default="TianChenMeiKuang.Entity" Optional="False" Category="Strings" Description="实体类命名空间" %>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="Context" Description="源表" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Assembly Name="System.Data" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Import Namespace="System.Data" %>
/**********************************************************
 Name:<%= GetClassName(SourceTable) %>
 Author:
 Date:<%=DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") %>
 Description:
 Modify Remark:
**********************************************************/
using System;
using WebApp.Matrix.Data;

namespace <%=Namespace%>
{
    /// <summary>
    /// This Entity is Mapping To [<%=SourceTable.Name%>] Table
    /// Remark Ignore Attribute for the field when it is not need mapping
    /// </summary>
    [Serializable]
    [TableName("[<%=SourceTable.Name%>]")]
    <% 
    ColumnSchema primaryKeyColumn = GetPrimaryKeyColumn();
    if(primaryKeyColumn != null)
    {
        if(Convert.ToBoolean(primaryKeyColumn.ExtendedProperties["CS_isIdentity"].Value)==true){ %>
    [PrimaryKey("<%=primaryKeyColumn.Name%>", autoIncrement=true)]
        <% } 
        else {
        %>
    [PrimaryKey("<%=primaryKeyColumn.Name%>", autoIncrement=false)]
        <% }
    }%>
    public class <%= GetClassName(SourceTable) %>
    {        
        <% for (int i = 0; i < SourceTable.Columns.Count; i++) { %>
        /// <summary>
        /// <%= SourceTable.Columns[i].Name %>
        /// </summary>
        public <%= GetCSharpVariableType(SourceTable.Columns[i]) %> <%= GetPropertyName(SourceTable.Columns[i]) %>
        {
            get; set;
        }
        <% if (i < SourceTable.Columns.Count - 1) Response.Write("\r\n"); %>        
        <% } %>
        
        /// <summary>
        /// Equals
        /// </summary>
        public override bool Equals(object obj)
        {
            <%= GetClassName(SourceTable) %> other = obj as <%= GetClassName(SourceTable) %>;
            if (<%=GetFirstKeyCondition()%>)
            {
                return false;
            }
            if (<%=GetTwoKeyCondition()%>)
            {
                return false;
            }
            return true;
        }
        /// <summary>
        /// GetHashCode
        /// </summary>
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }
    }
}

<script runat="template">
public string GetClassName(TableSchema table)
{
    string className = table.Name;
    return className;
}
public string GetPropertyName(ColumnSchema column)
{
    string propertyName = column.Name;
    
    return propertyName;
}
public string GetFieldName(ColumnSchema column)
{
    string propertyName = column.Name;
    return propertyName;
}
public ColumnSchema GetPrimaryKeyColumn()
{
    for (int i = 0; i < SourceTable.Columns.Count; i++)
    {
        if(SourceTable.Columns[i].IsPrimaryKeyMember)
        {
            return     SourceTable.Columns[i];
        }
    }
    return null;
}
public string GetKey()
{
    for (int i = 0; i < SourceTable.Columns.Count; i++)
    {
        if(SourceTable.Columns[i].IsPrimaryKeyMember)
        {
            return     SourceTable.Columns[i].Name;
        }
    }
    return "GetHashCode().ToString()";
}
public string GetCSharpVariableType(ColumnSchema column)
{
    switch (column.DataType)
    {
        case DbType.AnsiString: return "string";
        case DbType.AnsiStringFixedLength: return "string";
        case DbType.Binary: return "Nullable<int>";
        case DbType.Boolean: if(column.AllowDBNull){return "Nullable<bool>";}else{return "bool";};
        case DbType.Byte: return "int";
        case DbType.Currency: if(column.AllowDBNull){return "Nullable<decimal>";}else{return "decimal";};
        case DbType.Date: if(column.AllowDBNull){return "Nullable<DateTime>";}else{return "DateTime";};
        case DbType.DateTime: if(column.AllowDBNull){return "Nullable<DateTime>";}else{return "DateTime";};
        case DbType.Decimal: if(column.AllowDBNull){return "Nullable<decimal>";}else{return "decimal";};
        case DbType.Double: if(column.AllowDBNull){return "Nullable<double>";}else{return "double";};
        case DbType.Guid: return "Guid";
        case DbType.Int16: if(column.AllowDBNull){return "Nullable<short>";}else{return "short";};
        case DbType.Int32: if(column.AllowDBNull){return "Nullable<int>";}else{return "int";};
        case DbType.Int64: if(column.AllowDBNull){return "Nullable<long>";}else{return "long";};
        case DbType.Object: return "object";
        case DbType.SByte: if(column.AllowDBNull){return "Nullable<sbyte>";}else{return "sbyte";};
        case DbType.Single: if(column.AllowDBNull){return "Nullable<float>";}else{return "float";};
        case DbType.String: return "string";
        case DbType.StringFixedLength: return "string";
        case DbType.Time: if(column.AllowDBNull){return "Nullable<TimeSpan>";}else{return "TimeSpan";};
        case DbType.UInt16: if(column.AllowDBNull){return "Nullable<ushort>";}else{return "ushort";};
        case DbType.UInt32: if(column.AllowDBNull){return "Nullable<uint>";}else{return "uint";};
        case DbType.UInt64: if(column.AllowDBNull){return "Nullable<ulong>";}else{return "ulong";};
        case DbType.VarNumeric: if(column.AllowDBNull){return "Nullable<decimal>";}else{return "decimal";};
        default:return "string";
    }
}
public string GetFirstKeyCondition()
{
    string condition = " other==null";
    for (int i = 0; i < SourceTable.Columns.Count; i++)
    {
        var tempColumn = SourceTable.Columns[i];
        if(tempColumn.IsPrimaryKeyMember)
        {
            if(((bool)tempColumn.ExtendedProperties["CS_IsIdentity"].Value))
            {
                condition += " || this." + SourceTable.Columns[i].Name + " == 0";
                condition += " || other."+ SourceTable.Columns[i].Name + " == 0";
            }
            else
            {
                condition += " || string.IsNullOrEmpty(this." + SourceTable.Columns[i].Name + ")";
                condition += " || string.IsNullOrEmpty(other."+ SourceTable.Columns[i].Name + ")";
            }
        }
    }
    return condition;
}
public string GetTwoKeyCondition()
{
    string condition = " ";
    for (int i = 0; i < SourceTable.Columns.Count; i++)
    {
        if(SourceTable.Columns[i].IsPrimaryKeyMember)
        {
             condition += " || this."+SourceTable.Columns[i].Name +" !=other."+SourceTable.Columns[i].Name;
        }
    }
    return condition.Substring(4,condition.Length-4).ToString();
}
public string GetHashCodeStr()
{
    string hashCode = " ";
    for (int i = 0; i < SourceTable.Columns.Count; i++)
    {
        if(SourceTable.Columns[i].IsPrimaryKeyMember)
        {
             hashCode += "+\"|\" +this."+SourceTable.Columns[i].Name +".ToLower()";
        }
    }
    return hashCode.Substring(7,hashCode.Length-7).ToString();
}
public string GetDefaultValue(ColumnSchema column)
{
    string DefaultValue = "";
    switch(column.DataType)
    {
        case DbType.Int16:
        case DbType.Int32:
        case DbType.Int64:
            DefaultValue = "0";    
            break;
        case DbType.Decimal:
            DefaultValue = "0.000000M";
            break;
        case DbType.AnsiString:
        case DbType.String:
        case DbType.StringFixedLength:
            DefaultValue = "\"\"";
            break;
        case DbType.Date:
        case DbType.DateTime:
        case DbType.DateTime2:
            DefaultValue = "DateTime.Parse(\"1999-01-01 00:00:00\")";
            break;
        case DbType.Binary:
            DefaultValue = "new byte[] { }";
            break;
        case DbType.Boolean:
            DefaultValue = "False";
            break;
        case DbType.Byte:
            DefaultValue = "1";
            break;
        default:
            break;
    }
    return DefaultValue;
}
</script>

该模板只适用于但主键的环境,且主键必须为字符串类型,或者为自增长列。初步满足公司当前的需要。

posted @ 2012-06-20 16:42  拓荒者FF  阅读(2538)  评论(0编辑  收藏  举报