其他层次的模板

在【CodeSmith快速入门之四:模型层的生成】中,我们介绍了模型层模板的生成,在本章我们将会介绍其他层次的模板。

因为每个层次的模板编写都比较类似,所以这次不会对模板代码进行详细的说明,尽请谅解,谢谢

1、数据访问接口代码生成模版


<%-- 
Name: 数据访问接口代码生成模版
Author: Fencer
Description: 根据数据库的内容生成数据访问层接口
Version: V1.
0 新规初成
--%>
<%@ CodeTemplate Language="C#" TargetLanguage="Text" ResponseEncoding="UTF-8"%>
<%Property Name="Namespace" Type="String" Default="IDAL" Category="内容" Description="命名空间名称" %>
<%Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="内容" Description="数据源表" %>
<%Property Name="ObjectName" Type="String" Category="注释" Description="对象名称,为生成注释而用" %>
<%@ Assembly Name="System.Data" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="SchemaExplorer" %>
using System;
using System.Collections.Generic;
using System.Text;

namespace 
<%=Namespace%>
{
    using Model;
    
    /// 
<summary>
    /// 
<%=ObjectName%>的数据访问操作
    /// 
</summary>
    public interface I
<%=GetModelName(SourceTable)%>
    {
        /// 
<summary>
        /// 添加
<%=ObjectName%>
        /// 
</summary>
        /// 
<param name="<%=GetModelParameterName(SourceTable)%>"><%=ObjectName%></param>
        /// 
<returns>最新编号</returns>
        int Add
<%=GetModelName(SourceTable)%>(<%=GetModelName(SourceTable)%> <%=GetModelParameterName(SourceTable)%>);
        
        /// 
<summary>
        /// 更新
<%=ObjectName%>
        /// 
</summary>
        /// 
<param name="<%=GetModelParameterName(SourceTable)%>"><%=ObjectName%></param>
        /// 
<returns>bool</returns>
        bool Update
<%=GetModelName(SourceTable)%>(<%=GetModelName(SourceTable)%> <%=GetModelParameterName(SourceTable)%>);
        
        /// 
<summary>
        /// 根据ID删除
<%=ObjectName%>
        /// 
</summary>
        /// 
<param name="<%=GetPrimaryKeyFieldName(SourceTable)%>"><%=ObjectName%>ID</param>
        /// 
<returns>bool</returns>
        bool Delete
<%=GetModelName(SourceTable)%>By<%=GetPrimaryKeyPropertyName(SourceTable)%>(<%=GetPrimaryKeyType(SourceTable)%> <%=GetPrimaryKeyFieldName(SourceTable)%>);
        
        /// 
<summary>
        /// 根据ID查询
<%=ObjectName%>
        /// 
</summary>
        /// 
<param name="<%=GetPrimaryKeyFieldName(SourceTable)%>"><%=ObjectName%>ID</param>
        /// 
<returns><%=ObjectName%>对象</returns>
        
<%=GetModelName(SourceTable)%> Get<%=GetModelName(SourceTable)%>By<%=GetPrimaryKeyPropertyName(SourceTable)%>(<%=GetPrimaryKeyType(SourceTable)%> <%=GetPrimaryKeyFieldName(SourceTable)%>);
        
        /// 
<summary>
        /// 获得所有
<%=ObjectName%>
        /// 
</summary>
        /// 
<returns><%=ObjectName%>集合</returns>
        IList
<<%=GetModelName(SourceTable)%>> GetAll<%=GetModelName(SourceTable)%>s();
    }
}

<script runat="template">
    public string GetClassName(TableSchema table)
    {
        string tempTable;
        
if (table.Name.EndsWith("s"))
        {
            tempTable 
= table.Name.Substring(0,table.Name.Length-1);
        }
        
else
        {
            tempTable 
= table.Name;
        }
        
return tempTable;
    }
    
    public string GetModelName(TableSchema table)
    {
        
return ConvertToPascal(GetClassName(table));
    }
    
    public string GetModelParameterName(TableSchema table)
    {
        
return ConvertToCamel(GetClassName(table));
    }
    
    public string GetPrimaryKeyType(TableSchema table)
    {
        
if (table.PrimaryKey != null)
        {
            
if (table.PrimaryKey.MemberColumns.Count == 1)
            {
                
return GetCSharpDataTypeByDBColumn(table.PrimaryKey.MemberColumns[0]);
            }
            
else
            {
                
throw new ApplicationException("此模板只支持单个列的主键");
            }
        }
        
else
        {
            
throw new ApplicationException("此模板需要有主键的表");
        }
    }
    
    public string GetPrimaryKeyName(TableSchema table)
    {
        
if (table.PrimaryKey != null)
        {
            
if (table.PrimaryKey.MemberColumns.Count == 1)
            {
                
return table.PrimaryKey.MemberColumns[0].Name;
            }
            
else
            {
                
throw new ApplicationException("此模板只支持单个列的主键");
            }
        }
        
else
        {
            
throw new ApplicationException("此模板需要有主键的表");
        }
    }
    
    public string GetPrimaryKeyFieldName(TableSchema table)
    {
        
return ConvertToCamel(GetPrimaryKeyName(table));
    }
    
    public string GetPrimaryKeyPropertyName(TableSchema table)
    {
        
return ConvertToPascal(GetPrimaryKeyName(table));
    }
    
    public string GetCSharpDataTypeByDBColumn(ColumnSchema column)
    {
        
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 ConvertToPascal(string str)
    {
        
return str.Substring(0,1).ToUpper() + str.Substring(1);
    }
    
    public string ConvertToCamel(string str)
    {
        
return str.Substring(0,1).ToLower() + str.Substring(1);
    }
    
    public override string GetFileName()
    {
        
return "I" + GetModelName(SourceTable) + ".cs";
    }
</script>

 

2、数据访问层代码生成模版


<%-- 
Name: 数据访问层代码生成模版
Author: Fencer
Description: 根据数据库的内容生成模型层代码
Version: V1.
0 新规初成
--%>
<%@ CodeTemplate Language="C#" TargetLanguage="Text" ResponseEncoding="UTF-8"%>
<%Property Name="Namespace" Type="String" Default="SQLServerDAL" Category="内容" Description="命名空间名称" %>
<%Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="内容" Description="数据源表" %>
<%Property Name="ObjectName" Type="String" Category="注释" Description="对象名称,为生成注释而用" %>
<%@ Assembly Name="System.Data" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="SchemaExplorer" %>
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace 
<%=Namespace%>
{
    using IDAL;
    using Model;
    using Common;
    
    /// 
<summary>
    /// 
<%=ObjectName%>的数据访问操作
    /// 
</summary>
    public class 
<%=GetModelName(SourceTable)%>s : I<%=GetModelName(SourceTable)%>
    {
        /// 
<summary>
        /// 添加
<%=ObjectName%>
        /// 
</summary>
        /// 
<param name="<%=GetModelParameterName(SourceTable)%>"><%=ObjectName%></param>
        /// 
<returns>最新编号</returns>
        public int Add
<%=GetModelName(SourceTable)%>(<%=GetModelName(SourceTable)%> <%=GetModelParameterName(SourceTable)%>)
        {
            string sql = 
<%=GetInsertSql()%>;
            
            SqlParameter[] pas = new SqlParameter[]
                {
                    
<%
                        
for(int i=0; i<SourceTable.NonPrimaryKeyColumns.Count; i++)
                        {
                            ColumnSchema column 
= SourceTable.NonPrimaryKeyColumns[i];
                    
%>
                    new SqlParameter("@
<%=column.Name%>",SqlDbType.<%=GetSqlDbType(column)%>,<%=column.Size%>)<%= (i==(SourceTable.NonPrimaryKeyColumns.Count-1)? "":",")%>
                    
<%
                        }
                    
%>
                };
            
            
<%
                
for(int i=0; i<SourceTable.NonPrimaryKeyColumns.Count; i++)
                {
            
%>
            pas[
<%=i%>].Value = <%=GetModelParameterName(SourceTable)%>.<%=SourceTable.NonPrimaryKeyColumns[i].Name%>;
            
<%
                }
            
%>
            
            return Convert.ToInt32(SqlHelper.ExecuteScalar(SqlHelper.CONN_STRING, CommandType.Text, sql, pas));
        }
        
        /// 
<summary>
        /// 更新
<%=ObjectName%>
        /// 
</summary>
        /// 
<param name="<%=GetModelParameterName(SourceTable)%>"><%=ObjectName%></param>
        /// 
<returns>bool</returns>
        public bool Update
<%=GetModelName(SourceTable)%>(<%=GetModelName(SourceTable)%> <%=GetModelParameterName(SourceTable)%>)
        {
            string sql = 
<%=GetUpdateSql()%>;
            
            SqlParameter[] pas = new SqlParameter[]
                {
                    
<%
                        
for(int i=0; i<SourceTable.NonPrimaryKeyColumns.Count; i++)
                        {
                            ColumnSchema column 
= SourceTable.NonPrimaryKeyColumns[i];
                    
%>
                    new SqlParameter("@
<%=column.Name%>",SqlDbType.<%=GetSqlDbType(column)%>,<%=column.Size%>),
                    
<%
                        }
                    
%>
                    new SqlParameter("@
<%=GetPrimaryKeyName(SourceTable)%>",SqlDbType.<%=GetSqlDbType(GetPrimaryKeyColumn(SourceTable))%>,<%=GetPrimaryKeySize(SourceTable)%>)
                };
            
            
<%
                
for(int i=0; i<=SourceTable.NonPrimaryKeyColumns.Count; i++)
                {
                    
if (i < SourceTable.NonPrimaryKeyColumns.Count)
                    {
            
%>
            pas[
<%=i%>].Value = <%=GetModelParameterName(SourceTable)%>.<%=SourceTable.NonPrimaryKeyColumns[i].Name%>;
            
<%
                    }
                    
else
                    {
            
%>
            pas[
<%=i%>].Value = <%=GetModelParameterName(SourceTable)%>.<%=GetPrimaryKeyName(SourceTable)%>;
            
<%
                    }
                }
            
%>
            
            int rows = SqlHelper.ExecuteNonQuery(SqlHelper.CONN_STRING,CommandType.Text,sql,pas);
            return (rows == 1);
        } 
        
        /// 
<summary>
        /// 根据ID删除
<%=ObjectName%>
        /// 
</summary>
        /// 
<param name="<%=GetPrimaryKeyFieldName(SourceTable)%>"><%=ObjectName%>ID</param>
        /// 
<returns>bool</returns>
        public bool Delete
<%=GetModelName(SourceTable)%>By<%=GetPrimaryKeyPropertyName(SourceTable)%>(<%=GetPrimaryKeyType(SourceTable)%> <%=GetPrimaryKeyFieldName(SourceTable)%>)
        {
            string sql = "DELETE FROM 
<%=SourceTable.Name%> WHERE <%=GetPrimaryKeyName(SourceTable)%>=@<%=GetPrimaryKeyName(SourceTable)%>";
            
            SqlParameter pa = new SqlParameter("@
<%=GetPrimaryKeyName(SourceTable)%>",SqlDbType.<%=GetPrimaryKeySqlDbType(SourceTable)%>,<%=GetPrimaryKeySize(SourceTable)%>);
            pa.Value = 
<%=GetPrimaryKeyFieldName(SourceTable)%>;
            
            int rows = SqlHelper.ExecuteNonQuery(SqlHelper.CONN_STRING,CommandType.Text,sql,pa);
            
            return (rows == 1);
        }
        
        /// 
<summary>
        /// 根据ID查询
<%=ObjectName%>
        /// 
</summary>
        /// 
<param name="<%=GetPrimaryKeyFieldName(SourceTable)%>"><%=ObjectName%>ID</param>
        /// 
<returns><%=ObjectName%>对象</returns>
        public 
<%=GetModelName(SourceTable)%> Get<%=GetModelName(SourceTable)%>By<%=GetPrimaryKeyPropertyName(SourceTable)%>(<%=GetPrimaryKeyType(SourceTable)%> <%=GetPrimaryKeyFieldName(SourceTable)%>)
        {
            string sql = 
<%=GetSelectOneModelSql()%>;
            
            SqlParameter pa = new SqlParameter("@
<%=GetPrimaryKeyName(SourceTable)%>",SqlDbType.<%=GetPrimaryKeySqlDbType(SourceTable)%>,<%=GetPrimaryKeySize(SourceTable)%>);
            pa.Value = 
<%=GetPrimaryKeyFieldName(SourceTable)%>;
            
            using(SqlDataReader rdr = SqlHelper.ExecuteReader(
                SqlHelper.CONN_STRING,CommandType.Text,sql,pa))
            {
                if (rdr.Read())
                {
                    
<%=GetModelName(SourceTable)%> <%=GetModelParameterName(SourceTable)%> = new <%=GetModelName(SourceTable)%>();
                    
<%
                        foreach(ColumnSchema column in SourceTable.Columns)
                        {
                    
%>
                    
<%=GetModelParameterName(SourceTable)%>.<%=column.Name%> = (<%=GetCSharpDataTypeByDBColumn(column)%>)rdr["<%=column.Name%>"];
                    
<%
                        }
                    
%>
                    
                    return 
<%=GetModelParameterName(SourceTable)%>;
                }
            }
            
            return null;
        }
        
        /// 
<summary>
        /// 获得所有
<%=ObjectName%>
        /// 
</summary>
        /// 
<returns><%=ObjectName%>集合</returns>
        public IList
<<%=GetModelName(SourceTable)%>> GetAll<%=GetModelName(SourceTable)%>s()
        {
            string sql = 
<%=GetSelectAllModelSql()%>;
            
            IList
<<%=GetModelName(SourceTable)%>> all<%=GetModelName(SourceTable)%>s = new List<<%=GetModelName(SourceTable)%>>();
            
            using(SqlDataReader rdr = SqlHelper.ExecuteReader(
                SqlHelper.CONN_STRING,CommandType.Text,sql))
            {
                while (rdr.Read())
                {
                    
<%=GetModelName(SourceTable)%> <%=GetModelParameterName(SourceTable)%> = new <%=GetModelName(SourceTable)%>();
                    
<%
                        foreach(ColumnSchema column in SourceTable.Columns)
                        {
                    
%>
                    
<%=GetModelParameterName(SourceTable)%>.<%=column.Name%> = (<%=GetCSharpDataTypeByDBColumn(column)%>)rdr["<%=column.Name%>"];
                    
<%
                        }
                    
%>
                    
                    all
<%=GetModelName(SourceTable)%>s.Add(<%=GetModelParameterName(SourceTable)%>);
                }
            }
            
            return all
<%=GetModelName(SourceTable)%>s;
        }
    }
}

<script runat="template">
    public string GetClassName(TableSchema table)
    {
        string tempTable;
        
if (table.Name.EndsWith("s"))
        {
            tempTable 
= table.Name.Substring(0,table.Name.Length-1);
        }
        
else
        {
            tempTable 
= table.Name;
        }
        
return tempTable;
    }
    
    public string GetModelName(TableSchema table)
    {
        
return ConvertToPascal(GetClassName(table));
    }
    
    public string GetModelParameterName(TableSchema table)
    {
        
return ConvertToCamel(GetClassName(table));
    }
    
    public string GetPrimaryKeyType(TableSchema table)
    {
        
if (table.PrimaryKey != null)
        {
            
if (table.PrimaryKey.MemberColumns.Count == 1)
            {
                
return GetCSharpDataTypeByDBColumn(table.PrimaryKey.MemberColumns[0]);
            }
            
else
            {
                
throw new ApplicationException("此模板只支持单个列的主键");
            }
        }
        
else
        {
            
throw new ApplicationException("此模板需要有主键的表");
        }
    }
    
    public ColumnSchema GetPrimaryKeyColumn(TableSchema table)
    {
        
if (table.PrimaryKey != null)
        {
            
if (table.PrimaryKey.MemberColumns.Count == 1)
            {
                
return table.PrimaryKey.MemberColumns[0];
            }
            
else
            {
                
throw new ApplicationException("此模板只支持单个列的主键");
            }
        }
        
else
        {
            
throw new ApplicationException("此模板需要有主键的表");
        }
    }
    
    public string GetPrimaryKeyName(TableSchema table)
    {
        
if (table.PrimaryKey != null)
        {
            
if (table.PrimaryKey.MemberColumns.Count == 1)
            {
                
return table.PrimaryKey.MemberColumns[0].Name;
            }
            
else
            {
                
throw new ApplicationException("此模板只支持单个列的主键");
            }
        }
        
else
        {
            
throw new ApplicationException("此模板需要有主键的表");
        }
    }
    
    public string GetPrimaryKeySize(TableSchema table)
    {
        
return table.PrimaryKey.MemberColumns[0].Size.ToString();
    }
    
    public string GetPrimaryKeySqlDbType(TableSchema table)
    {
        
return GetSqlDbType(table.PrimaryKey.MemberColumns[0]);
    }
    
    public string GetPrimaryKeyFieldName(TableSchema table)
    {
        
return ConvertToCamel(GetPrimaryKeyName(table));
    }
    
    public string GetPrimaryKeyPropertyName(TableSchema table)
    {
        
return ConvertToPascal(GetPrimaryKeyName(table));
    }
    
    public string GetInsertSql()
    {
        string sql 
= "\"INSERT INTO " + SourceTable.Name + "(";
        foreach(ColumnSchema column in SourceTable.NonPrimaryKeyColumns)
        {
            sql += column.Name + 
",";
        }
        sql = sql.Substring(0,sql.Length-1);
        sql += 
")\" +\n";
        
        sql 
+= "\t\t\t\t\" values(";
        foreach(ColumnSchema column in SourceTable.NonPrimaryKeyColumns)
        {
            sql += 
"@" + column.Name + ",";
        }
        sql = sql.Substring(0,sql.Length-1);
        sql += 
");\" + \n";
        sql 
+= "\t\t\t\t\" SELECT SCOPE_IDENTITY();\"";
        
        
return sql;
    }
    
    public string GetUpdateSql()
    {
        string sql 
= "\"UPDATE " + SourceTable.Name + " \" +\n";
        sql 
+= "\t\t\t\t\"SET ";
        foreach(ColumnSchema column in SourceTable.NonPrimaryKeyColumns)
        {
            sql += column.Name + 
"=@" + column.Name + ",";
        }
        sql = sql.Substring(0,sql.Length-1);
        sql += 
" \" +\n";
        
        sql 
+= "\t\t\t\t\"WHERE " + GetPrimaryKeyName(SourceTable) + "=@" + GetPrimaryKeyName(SourceTable) + "\"";
        
        
return sql;
    }
    
    public string GetSelectOneModelSql()
    {
        string sql 
= "\"SELECT ";    
        foreach(ColumnSchema column in SourceTable.Columns)
        {
            sql += column.Name + 
",";
        }
        sql = sql.Substring(0,sql.Length-1);
        sql += 
" \" +\n";
        
        sql 
+= "\t\t\t\t\"FROM " + SourceTable.Name + " \" +\n";
        sql 
+= "\t\t\t\t\"WHERE " + GetPrimaryKeyName(SourceTable) + "=@" + GetPrimaryKeyName(SourceTable) + "\"";
        
        
return sql;
    }
    
    public string GetSelectAllModelSql()
    {
        string sql 
= "\"SELECT ";    
        foreach(ColumnSchema column in SourceTable.Columns)
        {
            sql += column.Name + 
",";
        }
        sql = sql.Substring(0,sql.Length-1);
        sql += 
" \" +\n";
        
        sql 
+= "\t\t\t\t\"FROM " + SourceTable.Name + "\"";
        
        
return sql;
    }

    
    public string GetCSharpDataTypeByDBColumn(ColumnSchema column)
    {
        
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 GetSqlDbType(ColumnSchema column)
    {
        
switch (column.NativeType)
        {
            
case "bigint"return "BigInt";
            
case "binary"return "Binary";
            
case "bit"return "Bit";
            
case "char"return "Char";
            
case "datetime"return "DateTime";
            
case "decimal"return "Decimal";
            
case "float"return "Float";
            
case "image"return "Image";
            
case "int"return "Int";
            
case "money"return "Money";
            
case "nchar"return "NChar";
            
case "ntext"return "NText";
            
case "numeric"return "Decimal";
            
case "nvarchar"return "NVarChar";
            
case "real"return "Real";
            
case "smalldatetime"return "SmallDateTime";
            
case "smallint"return "SmallInt";
            
case "smallmoney"return "SmallMoney";
            
case "sql_variant"return "Variant";
            
case "sysname"return "NChar";
            
case "text"return "Text";
            
case "timestamp"return "Timestamp";
            
case "tinyint"return "TinyInt";
            
case "uniqueidentifier"return "UniqueIdentifier";
            
case "varbinary"return "VarBinary";
            
case "varchar"return "VarChar";
            
defaultreturn "__UNKNOWN__" + column.NativeType;
        }
    }
    
    public string ConvertToPascal(string str)
    {
        
return str.Substring(0,1).ToUpper() + str.Substring(1);
    }
    
    public string ConvertToCamel(string str)
    {
        
return str.Substring(0,1).ToLower() + str.Substring(1);
    }
    
    public override string GetFileName()
    {
        
return GetModelName(SourceTable) + "s.cs";
    }
</script>

 

3、数据访问工厂代码生成模版


<%-- 
Name: 数据访问工厂代码生成模版
Author: Fencer
Description: 根据数据库的内容生成数据访问工厂
Version: V1.
0 新规初成
--%>
<%@ CodeTemplate Language="C#" TargetLanguage="Text" ResponseEncoding="UTF-8"%>
<%Property Name="Namespace" Type="String" Default="DALFactory" Category="内容" Description="命名空间名称" %>
<%Property Name="Database" Type="SchemaExplorer.DatabaseSchema" Category="内容" Description="目标数据库" %>
<%@ Assembly Name="System.Data" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="SchemaExplorer" %>
using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Reflection;

namespace 
<%=Namespace%>
{
    using IDAL;
    
    /// 
<summary>
    /// 数据访问工厂
    /// 
</summary>
    public sealed class DataAccess
    {
        private static readonly string path = ConfigurationManager.AppSettings["DAL"];
        
        
<%
            foreach(TableSchema table in Database.Tables)
            {
        
%>
        /// 
<summary>
        /// 
        /// 
</summary>
        /// 
<returns>接口</returns>
        public static I
<%=table.Name%> Create<%=table.Name%>()
        {
            string className = path + ".
<%=table.Name%>s";
            return (I
<%=table.Name%>)Assembly.Load(path).CreateInstance(className);
        }
        
        
<%    
            }
        
%>
    }
}

<script runat="template">
    public override string GetFileName()
    {
        
return "DataAccess.cs";
    }
</script>

 

4、业务层代码生成模版


<%-- 
Name: 业务层代码生成模版
Author: Fencer
Description: 根据数据库的内容生成业务层代码
Version: V1.
0 新规初成
--%>
<%@ CodeTemplate Language="C#" TargetLanguage="Text" ResponseEncoding="UTF-8"%>
<%Property Name="BLLNamespace" Type="String" Default="BLL" Category="内容" Description="业务层命名空间名称" %>
<%Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="内容" Description="数据源表" %>
<%Property Name="ObjectName" Type="String" Category="注释" Description="对象名称,为生成注释而用" %>
<%@ Assembly Name="System.Data" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="SchemaExplorer" %>
using System;
using System.Collections.Generic;
using System.Text;

namespace 
<%=BLLNamespace%>
{
    using IDAL;
    using Model;
    using DALFactory;
    
    /// 
<summary>
    /// 
<%=ObjectName%>的业务处理类
    /// 
</summary>
    public class 
<%=GetModelName(SourceTable)%>BLL
    {
        private static readonly I
<%=GetModelName(SourceTable)%> dal = DataAccess.Create<%=GetModelName(SourceTable)%>();
        
        /// 
<summary>
        /// 添加
<%=ObjectName%>
        /// 
</summary>
        /// 
<param name="<%=GetModelParameterName(SourceTable)%>"><%=ObjectName%></param>
        /// 
<returns>最新编号</returns>
        public static int Add
<%=GetModelName(SourceTable)%>(<%=GetModelName(SourceTable)%> <%=GetModelParameterName(SourceTable)%>)
        {
            return dal.Add
<%=GetModelName(SourceTable)%>(<%=GetModelParameterName(SourceTable)%>);
        }
        
        /// 
<summary>
        /// 更新
<%=ObjectName%>
        /// 
</summary>
        /// 
<param name="<%=GetModelParameterName(SourceTable)%>"><%=ObjectName%></param>
        /// 
<returns>bool</returns>
        public static bool Update
<%=GetModelName(SourceTable)%>(<%=GetModelName(SourceTable)%> <%=GetModelParameterName(SourceTable)%>)
        {
            return dal.Update
<%=GetModelName(SourceTable)%>(<%=GetModelParameterName(SourceTable)%>);
        }
        
        /// 
<summary>
        /// 根据ID删除
<%=ObjectName%>
        /// 
</summary>
        /// 
<param name="<%=GetPrimaryKeyFieldName(SourceTable)%>"><%=ObjectName%>ID</param>
        /// 
<returns>bool</returns>
        public static bool Delete
<%=GetModelName(SourceTable)%>By<%=GetPrimaryKeyPropertyName(SourceTable)%>(<%=GetPrimaryKeyType(SourceTable)%> <%=GetPrimaryKeyFieldName(SourceTable)%>)
        {
            return dal.Delete
<%=GetModelName(SourceTable)%>By<%=GetPrimaryKeyPropertyName(SourceTable)%>(<%=GetPrimaryKeyFieldName(SourceTable)%>);
        }
        
        /// 
<summary>
        /// 根据ID查询
<%=ObjectName%>
        /// 
</summary>
        /// 
<param name="<%=GetPrimaryKeyFieldName(SourceTable)%>"><%=ObjectName%>ID</param>
        /// 
<returns><%=ObjectName%>对象</returns>
        public static 
<%=GetModelName(SourceTable)%> Get<%=GetModelName(SourceTable)%>By<%=GetPrimaryKeyPropertyName(SourceTable)%>(<%=GetPrimaryKeyType(SourceTable)%> <%=GetPrimaryKeyFieldName(SourceTable)%>)
        {
            return dal.Get
<%=GetModelName(SourceTable)%>By<%=GetPrimaryKeyPropertyName(SourceTable)%>(<%=GetPrimaryKeyFieldName(SourceTable)%>);
        }
        
        /// 
<summary>
        /// 获得所有
<%=ObjectName%>
        /// 
</summary>
        /// 
<returns><%=ObjectName%>集合</returns>
        public static IList
<<%=GetModelName(SourceTable)%>> GetAll<%=GetModelName(SourceTable)%>s()
        {
            return dal.GetAll
<%=GetModelName(SourceTable)%>s();
        }
    }
}

<script runat="template">
    public string GetClassName(TableSchema table)
    {
        string tempTable;
        
if (table.Name.EndsWith("s"))
        {
            tempTable 
= table.Name.Substring(0,table.Name.Length-1);
        }
        
else
        {
            tempTable 
= table.Name;
        }
        
return tempTable;
    }
    
    public string GetModelName(TableSchema table)
    {
        
return ConvertToPascal(GetClassName(table));
    }
    
    public string GetModelParameterName(TableSchema table)
    {
        
return ConvertToCamel(GetClassName(table));
    }
    
    public string GetPrimaryKeyName(TableSchema table)
    {
        
if (table.PrimaryKey != null)
        {
            
if (table.PrimaryKey.MemberColumns.Count == 1)
            {
                
return table.PrimaryKey.MemberColumns[0].Name;
            }
            
else
            {
                
throw new ApplicationException("此模板只支持单个列的主键");
            }
        }
        
else
        {
            
throw new ApplicationException("此模板需要有主键的表");
        }
    }
    
    public string GetPrimaryKeyType(TableSchema table)
    {
        
if (table.PrimaryKey != null)
        {
            
if (table.PrimaryKey.MemberColumns.Count == 1)
            {
                
return GetCSharpDataTypeByDBColumn(table.PrimaryKey.MemberColumns[0]);
            }
            
else
            {
                
throw new ApplicationException("此模板只支持单个列的主键");
            }
        }
        
else
        {
            
throw new ApplicationException("此模板需要有主键的表");
        }
    }
    
    public string GetCSharpDataTypeByDBColumn(ColumnSchema column)
    {
        
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 GetPrimaryKeyFieldName(TableSchema table)
    {
        
return ConvertToCamel(GetPrimaryKeyName(table));
    }
    
    public string GetPrimaryKeyPropertyName(TableSchema table)
    {
        
return ConvertToPascal(GetPrimaryKeyName(table));
    }
    
    public string ConvertToPascal(string str)
    {
        
return str.Substring(0,1).ToUpper() + str.Substring(1);
    }
    
    public string ConvertToCamel(string str)
    {
        
return str.Substring(0,1).ToLower() + str.Substring(1);
    }
    
    public override string GetFileName()
    {
        
return GetModelName(SourceTable) + "BLL.cs";
    }
</script>

 

好了,到本章为止主要的模板就都已经开发完了(此模板都比较简单,大家可以根据实际情况进行修改)  下载所有的模板(附带SqlHelper)。

问题:每次代码生成时都需要一个个模板运行,然后COPY->PASTE,是不是太麻烦了,下次会跟大家介绍怎么进行模板的调用,“一键”搭建起项目,谢谢。

你可能感兴趣的:(模板)