CodeSmith模板(生成數據訪問層)


i_f24.gif還是老套路,先是爲一張表寫模板。

<%@ Template Language="C#" TargetLanguage="C#" %>
<%@ Assembly Name="SchemaExplorer"%>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Property Name="SourceTable" Type="TableSchema"%>
<%@ Property Name="ModelNameSpace" Type="System.String" Default="Model" %>
<%@ Property Name="SQL_ServerDALNameSpace" Type="System.string" Default="SQL_ServerDAL" %>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IDAL;
using System.Data.SqlClient;
using System.Data;
using <%=ModelNameSpace%>;
namespace <%=SQL_ServerDALNameSpace %>
{
   public class <%=this.GetClassName()%>Service:<%=GetInterFaceName() %>
   {
       BDHelper db = new BDHelper();
       //插入一條記錄
        void Add<%=this.GetClassName()%>(<%=this.GetClassName()%> <%=this.ToCamel(this.GetClassName())%>)
        {
            string sql = "Insert into <%=this.SourceTable.Name%> <%=GetAddSqlStatement()%>";
            SqlParameter[] ps = new SqlParameter[] {
               <%=GetAddSQLParameters() %>
            };
            db.ExecuteNonQury(sql,ps);
        }  
        //根據主鍵更新
       public void Update<%=this.GetClassName()%>(<%=this.GetClassName()%> <%=this.ToCamel(this.GetClassName())%>)
        {
            string sql = "Update <%=this.SourceTable.Name%> set <%=GetSetSuffix()%> where <%=GetPKSqlParameters()%>";
            SqlParameter[] ps = new SqlParameter[] {
                <%=GetUptdateSQLParameters() %>
            };
            db.ExecuteNonQury(sql, ps);
        }
        //根據唯一索引刪除
        <%foreach(IndexSchema index in this.SourceTable.Indexes){%>      
        public void Delete<%=this.GetClassName()%>By<%=GetUniqueIndexBySuffix(index)%>(<%=GetUniqueIndexMethodParameters(index)%>)
        {
            string sql = "Delete From <%=this.SourceTable.Name%> Where <%=GetUniqueIndexSQLWhereParameters(index)%>";
            SqlParameter[] ps = new SqlParameter[] {
                <%=GetUniqueIndexSQLParameters(index) %>
            };
            return db.ExecuteNonQuery(sql, ps);
        }
        <%}%>
        //根據外鍵刪除
         <%foreach(TableKeySchema key in this.SourceTable.ForeignKeys) {%>
        public void Delete<%=this.GetClassName()%>By<%=GetFKBySuffix(key)%>(<%=GetFKMethodParameters(key)%>)
        {
            string sql = "Delete From <%=this.SourceTable.Name%> Where <%=GetFKSQLWhereParameters(key)%>";
            SqlParameter[] ps = new SqlParameter[] {
                <%=GetFKSQLParameters(key) %>
            };
            return db.ExecuteNonQuery(sql, ps);
        }
        <%}%>
        //根據唯一索引查詢
       <%foreach(IndexSchema index in this.SourceTable.Indexes){%>
        public <%=this.GetClassName()%> Get<%=this.GetClassName()%>By<%=GetUniqueIndexBySuffix(index)%>(<%=GetUniqueIndexMethodParameters(index)%>)
        {
            string sql = "Select * from <%=this.SourceTable.Name%> where <%=GetUniqueIndexSQLWhereParameters(index)%>";
            SqlParameter[] ps = new SqlParameter[] {
                <%=GetUniqueIndexSQLParameters(index) %>
            };
            DataTable dt = db.GetTable(sql,ps);
            if (dt.Rows.Count==0)
            {
                return null;
            }
            DataRow dr=dt.Rows[0];
            <%=GetClassName() %> <%=ToCamel(GetClassName())%> = new <%=GetClassName()%>();
            <%=GetUniqueIndexSelect() %>
            return <%=ToCamel(GetClassName())%>;
        }
        <%}%>
        //根據外鍵查詢
        <%foreach(TableKeySchema key in this.SourceTable.ForeignKeys) {%>
        public List<<%=this.GetClassName()%>> Get<%=this.GetClassName()%>By<%=GetFKBySuffix(key)%>(<%=GetFKMethodParameters(key)%>)
        {
            string sql = "Select * from <%=this.SourceTable.Name%> where <%=GetFKSQLWhereParameters(key)%>";
            SqlParameter[] ps = new SqlParameter[] {
                <%=GetFKSQLParameters(key) %>
            };
            DataTable dt = db.GetTable(sql,ps);
            DataRow dr=dt.Rows[0];
            if (dt.Rows.Count==0)
            {
                return null;
            }
            <%=GetClassName() %> <%=ToCamel(GetClassName())%> = new <%=GetClassName()%>();
            <%=GetUniqueIndexSelect() %>
            return <%=ToCamel(GetClassName())%>;
        }
        <%} %>
                                                
        public List<<%=this.GetClassName()%>> Get<%=this.GetClassName()%>s()
        {
            string sql = "Select * from <%=this.SourceTable.Name%>";
            SqlParameter[] ps = new SqlParameter[] { };
            DataTable dt = db.GetTable(sql, ps);
            List<<%=this.GetClassName()%>> list = new List<<%=this.GetClassName()%>>();
            foreach (DataRow dr in dt.Rows)
            {
                <%=this.GetClassName()%> <%=this.ToCamel(this.GetClassName())%> = new <%=this.ToCamel(this.GetClassName())%>();
                <%=GetUniqueIndexSelect() %>
                list.Add(<%=this.ToCamel(this.GetClassName())%>);
            }
            return list;
        }
     }
}
<script runat="template">
public string GetUpdateSQLStatement()
{
    string fields="";
    foreach(ColumnSchema column in this.SourceTable.Columns)
    {
        bool b=(bool)column.ExtendedProperties["CS_IsIdentity"].Value;
        bool isPK=column.IsPrimaryKeyMember;
        if(!(b || isPK))
        {
            fields+=column.Name+"=@"+column.Name+",";
        }
    }
    if(fields!="")
    {
        fields=fields.Substring(0,fields.Length-1);
    }
                                            
                                            
    return fields;
}
//更新語句的參數數組
public string GetUptdateSQLParameters()
{
   string s="";
   foreach (ColumnSchema column in this.SourceTable.Columns)
   {
       bool b=(bool)column.ExtendedProperties["CS_IsIdentity"].Value;
       bool IsPK=column.IsPrimaryKeyMember;
       if (!(b && !IsPK))//參數裏面:是標識列並且不是主鍵的列不能出現
        {
            s+=string.Format("\t\t\t\tnew SqlParameter(\"@{0}\",{1}.{2}),\r\n",column.Name,ToCamel(this.GetClassName()),ToPascal(column.Name));   
        }
        if(s!="")
        {
            return s.Substring(0,s.Length-3).Substring(4);
        }   
    }
    return s;
}
//插入語句的參數數組
public string GetAddSQLParameters()
 {
    string s="";
    foreach (ColumnSchema column in this.SourceTable.Columns)
       {
           bool b=(bool)column.ExtendedProperties["CS_IsIdentity"].Value;
           if (!b)
           {
              s+=string.Format("\t\t\t\tnew SqlParameter(\"@{0}\",{1}.{2}),\r\n",column.Name,ToCamel(this.GetClassName()),ToPascal(column.Name));
           }
       }
          if (s!="")
          {
             return s.Substring(0,s.Length-3).Substring(4);
          }
      return s;
 } 
//插入語句的“()values()”部分
public string GetAddSqlStatement()
{
    string fields="";
    string values=""; 
    //遍歷所有的列名
    foreach (ColumnSchema column in this.SourceTable.Columns)
    {
        //獲取是否是標識列的屬性
        bool b=(bool)column.ExtendedProperties["CS_IsIdentity"].Value;
        if (!b)
        {
             fields+=column.Name+",";
             values+="@"+column.Name+",";
        }
    }
        if (fields!="")
        {
            fields=fields.Substring(0,fields.Length-1);               
        }
        if (values!="")
        {
            values=values.Substring(0,values.Length-1);
        }
        //利用格式化字符串的方法處理
        string s=string.Format("({0})values({1})",fields,values);
        return s;              
}
//根據唯一索引查詢一條記錄
public string GetUniqueIndexSelect()
{
    string s="";
    foreach (ColumnSchema column in this.SourceTable.Columns)
    {
         s+="\t\t\t\t"+ToCamel(GetClassName())+"."+ToPascal(column.Name) +"= ("+GetCSDataType(column)+")dr[\""+ToPascal(column.Name)+"\"];\n";
    }
    if (s!="")
    {
        return s.Substring(0,s.Length-1).Substring(4);
    }
    return s;
}
//獲取外鍵的參數列表
public string GetFKMethodParameters(TableKeySchema key)
{
    string s="";
    foreach(MemberColumnSchema column in key.ForeignKeyMemberColumns)
    {
        s+=GetCSDataType(column)+" "+ToCamel(column.Name)+",";
    }
    if(s!="")
    {
        return s.Substring(0,s.Length-1);
    }
    return s;
}
//得到方法名By之後的外鍵後綴
public string GetFKBySuffix(TableKeySchema key)
{
    string s="";
    //遍歷外鍵成員
    foreach(MemberColumnSchema column in key.ForeignKeyMemberColumns)
    {
        s+=ToPascal(column.Name)+"And";
    }
    if(s!="")
    {
        return s.Substring(0,s.Length-3);
    }
    return s;
}
//獲取Where之後的外鍵條件
public string GetFKSQLWhereParameters(TableKeySchema key)
{
    string s="";
    //遍歷外鍵成員
    foreach(MemberColumnSchema column in key.ForeignKeyMemberColumns)
    {
        s+=ToCamel(column.Name)+"=@"+ToCamel(column.Name)+" And ";   
    }
    if(s!="")
    {
        return s.Substring(0,s.Length-4);
    }
    return s;
}
//得到根據外鍵查詢或者刪除的參數數組
public string GetFKSQLParameters(TableKeySchema key)
{
    string s="";
    foreach(MemberColumnSchema column in key.ForeignKeyMemberColumns)
    {
        s+="\t\t\t\tnew SqlParameter(\"@"+ToCamel(column.Name)+"\","+ToCamel(column.Name)+"),\r\n";
    }
    if(s!="")
    {
        return s.Substring(0,s.Length-3).Substring(4);
    }
    return s;
}
//根據唯一索引查詢或者刪除的參數數組
public string GetUniqueIndexSQLParameters(IndexSchema index)
{
    string s="";
    //遍歷所有的索引成員
    foreach(MemberColumnSchema column in index.MemberColumns)
    {
        s+="\t\t\t\tnew SqlParameter(\"@"+ToCamel(column.Name)+"\","+ToCamel(column.Name)+"),\r\n";
    }
    if(s!="")
    {
        return s.Substring(0,s.Length-3).Substring(4);
    }
    return s;
}
//獲取根據唯一索引操作的Where條件部分
public string GetUniqueIndexSQLWhereParameters(IndexSchema index)
{
    string s="";
    //遍歷所有的索引成員
    foreach(MemberColumnSchema column in index.MemberColumns)
    {
        s+=ToCamel(column.Name)+"=@"+ToCamel(column.Name)+" And ";
    }
    if(s!="")
    {
        return s.Substring(0,s.Length-4);
    }
    return s;
}
//獲取根據唯一索引操作的參數列表
public string GetUniqueIndexMethodParameters(IndexSchema index)
{
    string s="";
    //遍歷所有的索引成員
    foreach(MemberColumnSchema column in index.MemberColumns)
    {
        s+=GetCSDataType(column)+" "+ToCamel(column.Name)+",";
    }
    if(s!="")
    {
        return s.Substring(0,s.Length-1);
    }
    return s;
}
//獲取根據唯一索引
public string GetUniqueIndexBySuffix(IndexSchema index)
{
    string s="";
    foreach(MemberColumnSchema column in index.MemberColumns)
    {
        s+=ToPascal(column.Name)+"And";
    }
    if(s!="")
    {
        return s.Substring(0,s.Length-3);
    }
    return s;
}
//找出所有的主鍵(作爲條件進行操作)
public string GetPKSqlParameters()
{
    string s="";
    //遍歷主鍵成員
    foreach (MemberColumnSchema column in this.SourceTable.PrimaryKey.MemberColumns)
    {
        s+=ToCamel(column.Name)+"=@"+ToCamel(column.Name)+" And ";
    } 
    if(s!="")
    {
        s=s.Substring(0,s.Length-4);
    }
    return s;
}
//得到更新語句SET後面的部分
public string GetSetSuffix()
{
    string s="";  
    foreach(ColumnSchema column in this.SourceTable.Columns)
    {
        bool b=(bool)column.ExtendedProperties["CS_IsIdentity"].Value;
        bool IsPK=column.IsPrimaryKeyMember;
        if (!(b||IsPK))//SET後面不能出現“是標識列或者是主鍵的列”
            {
                s+=ToCamel(column.Name)+"=@"+ToCamel(column.Name)+", ";
            }      
    }
    if (s!="")
        {
             s=s.Substring(0,s.Length-2);
        }
    return s;
}
//得到接口的名字
public string GetInterFaceName()
{
    string s=GetClassName();
    return "I"+s+"Service";
}
//Pascal命名法
public string ToPascal(string s)
{
    return s.Substring(0,1).ToUpper()+s.Substring(1);
}
//Camel命名法
public string ToCamel(string s)
{
    return s.Substring(0,1).ToLower()+s.Substring(1);
}
//得到實體類的類名
public string GetClassName()
{
    string s=this.SourceTable.Name;
    if(s.EndsWith("s"))
    {
        return ToPascal(s.Substring(0,s.Length-1));
    }
    return ToPascal(s);
}
//得到數據類型
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 string GetFileName()
    {
        return this.GetClassName()+"Service.cs";
    }
</script>

接下來是爲整個數據庫生成數據訪問層:

<%@ Template Language="C#" TargetLanguage="C#" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Property Name="SourceDB" Type="SchemaExplorer.DatabaseSchema" %>
<%@ Register Name="ServiceTempateClass" Template="SQLServerDALService.cst" %>
<%
foreach (TableSchema table in this.SourceDB.Tables)
    {
         ServiceTempateClass stc=new ServiceTempateClass();
         stc.SourceTable=table;
         stc.RenderToFile("f:\\模板類Service\\"+stc.GetFileName(),true);
    }
%>
<script runat="template">
</script>

雖然現在很辛苦,但是先苦後甜!一個功能強大模板給我們所帶來的好處遠遠超過我們花在模板身上的時間。所以,加油!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章