运用CodeSmith Studio实现C#项目构架

前言:运用CodeSmith Studio可以非常方便的针对具体的数据库生成C#项目的构架。本文将简要介绍操作流程。

准备工作:安装好CodeSmith Studio(网上一搜,到处都有下载)、Visual Studio、Mssql Server。

  1. 建立好数据库。假如数据库名叫SkillExchange。
  2. 启动CodeSmith,连接数据库。在Schema Explorer(如果主界面没有显示,在菜单View中将其打开)中点击“+”运用CodeSmith Studio实现C#项目构架图标,在弹出的【Data Source Manager】中选择【Add】。在弹出【Data Source】对话框中,自己给该数据源取一个名称,【Provider Type】选择【SqlSchemaProvider】,点击【Connection String】右侧的按钮,可以帮助生成连接字符串。之后点几个OK,一个Close,数据库连接就大功告成了。
  3. 使用模版生成3层代码。在模板管理器【Template Explorer】中选择模版,双击打开。这里要用到的项目构架代码可能找不到,我在这里提供。该模板来源于网络,也还有可以改进的地方。

  Model.cst(用于生成数据库表中字段的封装类,每个表生成一个类) 

MODEL

<%@ CodeTemplate Language="C#" TargetLanguage="C#" Description="Template description here." %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="Context" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
using System;
using System.Collections.Generic;
using System.Text;

namespace MODEL
{
    [Serializable]
    public class <%=GetClassName(SourceTable)%>
    {
        <% foreach (ColumnSchema column in SourceTable.Columns) {%>
        <% if (column.IsForeignKeyMember) {%>
        private <%=GetPascalName(GetForeignKeyColumnType(column))%> <%=GetCamelName(GetForeignKeyColumnName(column))%> = new <%=GetPascalName(GetForeignKeyColumnType(column))%>();
        <% }else{%>
        private <%=GetCSharpVariableType(column)%> <%=GetCamelName(column)%>;
        <% }%>
        <% }%>    
        
        <% foreach (ColumnSchema column in SourceTable.Columns) {%>
        <% if (column.IsForeignKeyMember) {%>
        public <%=GetPascalName(GetForeignKeyColumnType(column)) %> <%=GetPascalName(GetForeignKeyColumnName(column))%>
        {
            get { return <%=GetCamelName(GetForeignKeyColumnName(column)) %>; }
            set { <%=GetCamelName(GetForeignKeyColumnName(column)) %> = value; }
        }
        <% } else {%>
        public <%=GetCSharpVariableType(column) %> <%=GetPascalName(column) %>
        {
            get { return <%= GetCamelName(column) %>; }
            set { <%= GetCamelName(column) %> = value; }
        }
        <% }%>
        <% }%>
    }
}
<script runat="template">

public string MakeSingle(string name)
{
    return name;
}
public string GetCamelName(ColumnSchema column)
{
    return column.Name.Substring(0, 1).ToLower() + column.Name.Substring(1);
}
public string GetCamelName(string value)
{
    return value.Substring(0, 1).ToLower() + value.Substring(1);
}
public string GetPascalName(ColumnSchema column)
{
    return column.Name.Substring(0, 1).ToUpper() + column.Name.Substring(1);
}
public string GetPascalName(string value)
{
    return value.Substring(0, 1).ToUpper() + value.Substring(1);
}
public string GetClassName(TableSchema table)
{
    return GetPascalName(MakeSingle(table.Name));
}    
public string GetForeignKeyColumnType(ColumnSchema column)
{        
    return column.Table.ForeignKeys[0].PrimaryKeyTable.Name;
}
public string GetForeignKeyColumnName(ColumnSchema column)
{    
    if(column.Name.Substring(column.Name.Length-2).ToLower() == "id")
    {
        return column.Name.Substring(0,column.Name.Length-2);
    }
    else
    {
        return column.Name;
    }
}

public string GetStructureParameter()
{//int id,string name
        string temp = "";
        foreach(ColumnSchema column in SourceTable.NonPrimaryKeyColumns) 
        {
                if(column.IsForeignKeyMember) 
                {
                    temp += GetPascalName(GetForeignKeyColumnType(column)) + " " +GetCamelName(GetForeignKeyColumnName(column)) + ",";
                }
                else
                {
                    temp += GetCSharpVariableType(column) + " " + GetCamelName(column) + ",";
                }
        }
        return temp.Substring(0,temp.Length-1);
}
public string GetPrimaryKeyType(TableSchema table)
{
    if (table.PrimaryKey != null)
    {
        if (table.PrimaryKey.MemberColumns.Count == 1)
        {
            return GetCSharpVariableType(table.PrimaryKey.MemberColumns[0]);
        }
        else
        {
            throw new ApplicationException("This template will not work on primary keys with more than one member column.");
        }
    }
    else
    {
        throw new ApplicationException("This template will only work on tables with a primary key.");
    }
}
public string GetCSharpVariableType(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     GetClassName(SourceTable) + ".cs";
}
</script>

  DAL.cst(Data Access Layer,用于生成数据库的增删改查类)

DAL

<%@ CodeTemplate Language="C#" TargetLanguage="C#" Description="Create:Teacher Pan"%>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="Context" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using MODEL;

namespace DAL
{
    public class <%=GetClassName(SourceTable)%>Service
    {
        private const string SQL_INSERT_<%=SourceTable.Name.ToUpper()%> = "<%=GetAddConstString(SourceTable)%>";
        private const string SQL_UPDATE_<%=SourceTable.Name.ToUpper()%> = "<%=GetUpdateConstString(SourceTable)%>";
        private const string SQL_DELETE_<%=SourceTable.Name.ToUpper()%>_BY_ID = "<%=GetDeleteConstString(SourceTable)%>";
        private const string SQL_SELECT_<%=SourceTable.Name.ToUpper()%>_ALL = "SELECT * FROM <%=SourceTable.Name%>";
        private const string SQL_SELECT_ONE_<%=SourceTable.Name.ToUpper()%>_BY_ID = "SELECT * FROM <%=SourceTable.Name%> WHERE <%=GetPascalName(SourceTable.PrimaryKey.MemberColumns[0].Name)%>=@<%=GetPascalName(SourceTable.PrimaryKey.MemberColumns[0].Name)%>";

        public static int Add<%=GetClassName(SourceTable)%>(<%=GetClassName(SourceTable)%> <%=GetCamelName(GetClassName(SourceTable))%>)
        {
            <%=GetAddMothodText(SourceTable)%>
        }
    
        public static int Update<%=GetClassName(SourceTable)%>(<%=GetClassName(SourceTable)%> <%=GetCamelName(GetClassName(SourceTable))%>)
        {
            <%=GetUpdateMothodText(SourceTable)%>
        }
    
        public static int Delete<%=GetClassName(SourceTable)%>ById(<%=GetCSharpVariableType(SourceTable.PrimaryKey.MemberColumns[0].Column)%> id)
        {
            <%=GetDeleteMothodText(SourceTable)%>
        }
    
        public static List<<%=GetClassName(SourceTable)%>> GetAll<%=SourceTable.Name%>()
        {
            return Get<%=SourceTable.Name%>BySql(CommandType.Text, SQL_SELECT_<%=SourceTable.Name.ToUpper()%>_ALL, null);
        }
    
        public static <%=GetClassName(SourceTable)%> Get<%=GetClassName(SourceTable)%>ById(<%=GetCSharpVariableType(SourceTable.PrimaryKey.MemberColumns[0].Column)%> id)
        {
            SqlParameter commandParameters = new SqlParameter("@<%=GetPascalName(SourceTable.PrimaryKey.MemberColumns[0].Name)%>",id);
            List<<%=GetClassName(SourceTable)%>> list = Get<%=SourceTable.Name%>BySql(CommandType.Text ,SQL_SELECT_ONE_<%= SourceTable.Name.ToUpper() %>_BY_ID, commandParameters);
            if (list.Count > 0)
            {
                return list[0];
            }
            return null;
        }
    
        private static List<<%=GetClassName(SourceTable)%>> Get<%=SourceTable.Name%>BySql(CommandType commandType, string commandText, params SqlParameter[] commandParameters)
        { 
            List<<%=GetClassName(SourceTable)%>> list = new List<<%=GetClassName(SourceTable)%>>();
            using(SqlDataReader reader = DBHelper.ExecuteGetReader(commandType,commandText,commandParameters))
            {
                List<string> columnNames = new List<string>();
                for (int i = 0; i < reader.FieldCount; i++)
                {
                    columnNames.Add(reader.GetName(i));
                }
                while (reader.Read())
                {
                    <%=GetClassName(SourceTable)%> <%=GetCamelName(GetClassName(SourceTable))%> = new <%=GetClassName(SourceTable)%>();
                
                    //NonForeignKey                    
                    <%=GetNonForeignKeyColumnsText(SourceTable)%>
                    <%if(SourceTable.ForeignKeys.Count > 0){%>                    
                    //ForeignKey
                    <%for(int i=0;i<SourceTable.ForeignKeys.Count;i++){%>
                    <%=GetForeignKeyTableNewObjectText(SourceTable.ForeignKeys[i].PrimaryKeyTable,SourceTable.ForeignKeys[i].ForeignKeyMemberColumns[0])%>
                    <%=GetForeignKeyColumnsText(SourceTable.ForeignKeys[i].PrimaryKeyTable,SourceTable.ForeignKeys[i].ForeignKeyMemberColumns[0])%>                    
                    <%=AddForeignKeyObjectInPrimaryObject(SourceTable.ForeignKeys[i].PrimaryKeyTable,SourceTable.ForeignKeys[i].ForeignKeyMemberColumns[0])%>
                    <%}%>                    
                    <%}%>                    
                    list.Add(<%=GetCamelName(GetClassName(SourceTable))%>);
                }
            }
            return list;
        }
      }
}

<script runat="template">
public string GetCSharpVariableType(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 GetClassName(TableSchema table)
{    //need update ....    
    return GetPascalName(MakeSingle(table.Name));  //ToPascalName
}
public string GetPascalName(string name)
{
    return name.Substring(0,1).ToUpper() + name.Substring(1);
}
public string GetCamelName(string name)
{
    return name.Substring(0,1).ToLower() + name.Substring(1);
}
public string GetPrimaryKeyName(TableSchema table)
{
    return SourceTable.PrimaryKey.MemberColumns[0].Name;    
}
public string GetForeignKeyColumnType(ColumnSchema column)
{        
    return column.Table.ForeignKeys[0].PrimaryKeyTable.Name;
}
public string GetForeignKeyColumnName(ColumnSchema column)
{    
    if(column.Name.Substring(column.Name.Length-2).ToLower() == "id")
    {
        return column.Name.Substring(0,column.Name.Length-2);
    }
    else
    {
        return column.Name;
    }
}
public string GetForeignKeyTablePrimaryColumn(ColumnSchema column)
{    
    return column.Table.ForeignKeys[0].PrimaryKeyTable.PrimaryKey.MemberColumns[0].Name;
}
/**/
public string MakeSingle(string name)
{
    return name;
}

public string GetAddConstString(TableSchema SourceTable)
{
    string temp = "INSERT INTO "+ SourceTable.Name +" VALUES (";
  foreach(ColumnSchema column in SourceTable.NonPrimaryKeyColumns)
    {
        temp += "@" + GetPascalName(column.Name) + ",";
    }
    return temp.Substring(0,temp.Length-1) + ");SELECT @@IDENTITY";
}
public string GetUpdateConstString(TableSchema SourceTable)
{
    //update x set title=@title,,,, where id=@id;
    string temp = "UPDATE " + SourceTable.Name +" SET ";
    foreach(ColumnSchema column in SourceTable.NonPrimaryKeyColumns)
    {
        temp += GetPascalName(column.Name) +"=@" + GetPascalName(column.Name) + ",";
    }
    return temp.Substring(0,temp.Length-1) + " WHERE " + GetPascalName(SourceTable.PrimaryKey.MemberColumns[0].Name) + "=@" + GetPascalName(SourceTable.PrimaryKey.MemberColumns[0].Name);
}
public string GetDeleteConstString(TableSchema SourceTable)
{
    //delete from table where id=@id;
    string temp = "DELETE FROM " + SourceTable.Name + " WHERE " + GetPascalName(SourceTable.PrimaryKey.MemberColumns[0].Name) + "=@" + GetPascalName(SourceTable.PrimaryKey.MemberColumns[0].Name);
    return temp;
}
/*MothodText*/
public string GetAddMothodText(TableSchema SourceTable)
{
    string temp = "SqlParameter[] commandParameters = new SqlParameter[]" + "\r\n" 
                + "\t\t\t"+ "{" +"\r\n";
    foreach(ColumnSchema column in SourceTable.NonPrimaryKeyColumns)
    {   
            if(column.IsForeignKeyMember)            
                temp += "\t\t\t\t"+"new SqlParameter(\"@" + GetPascalName(column.Name) + "\", " + GetCamelName(GetClassName(SourceTable)) + "." + GetPascalName(GetForeignKeyColumnName(column)) + "."+ GetForeignKeyTablePrimaryColumn(column) +"),\r\n";        
            else
                temp += "\t\t\t\t"+"new SqlParameter(\"@" + GetPascalName(column.Name) + "\", " + GetCamelName(GetClassName(SourceTable)) + "." + GetPascalName(column.Name) + "),\r\n";        
    }
    temp = temp.Substring(0,temp.Length-3) + "\r\n\t\t\t};";
    temp += "\r\n\t\t\t"+ "int id = Convert.ToInt32(DBHelper.ExecuteScalar(CommandType.Text, SQL_INSERT_" + SourceTable.Name.ToUpper() +", commandParameters));\r\n"; 
  temp += "\t\t\t"+"return id;";             
  return temp;        
}
public string GetUpdateMothodText(TableSchema SourceTable)
{
    string temp = "SqlParameter[] commandParameters = new SqlParameter[]" + "\r\n" 
                + "\t\t\t"+ "{" +"\r\n";
      foreach(ColumnSchema column in SourceTable.Columns)
    {   
            if(column.IsForeignKeyMember)    
                temp += "\t\t\t\t"+"new SqlParameter(\"@" + GetPascalName(column.Name) + "\", " + GetCamelName(GetClassName(SourceTable)) + "." + GetPascalName(GetForeignKeyColumnName(column)) + "."+ GetForeignKeyTablePrimaryColumn(column) +"),\r\n";            
            else
                temp += "\t\t\t\t"+"new SqlParameter(\"@" + GetPascalName(column.Name) + "\", " + GetCamelName(GetClassName(SourceTable)) + "." + GetPascalName(column.Name) + "),\r\n";        
    }
    temp = temp.Substring(0,temp.Length-3) + "\r\n\t\t\t};";
    temp += "\r\n\t\t\t"+ "int rowCount = Convert.ToInt32(DBHelper.ExecuteNonQuery(CommandType.Text, SQL_UPDATE_"+ SourceTable.Name.ToUpper() +", commandParameters));\r\n"; 
  temp += "\t\t\t"+"return rowCount;";             
  return temp;        
}
public string GetDeleteMothodText(TableSchema SourceTable)
{
    string temp = "SqlParameter commandParameters = new SqlParameter(\"@" + GetPascalName(GetPrimaryKeyName(SourceTable)) +"\", id);";
    temp += "\r\n\t\t\t"+ "int rowCount = Convert.ToInt32(DBHelper.ExecuteNonQuery(CommandType.Text, SQL_DELETE_"+ SourceTable.Name.ToUpper() +"_BY_ID, commandParameters));\r\n"; 
  temp += "\t\t\t"+"return rowCount;";             
  return temp;
}
public string GetNonForeignKeyColumnsText(TableSchema SourceTable)
{   //book.Id = (int)row["Id"];
    //book.Title = (string)row["Title"];
    string className = GetCamelName(GetClassName(SourceTable));
    string temp = "";
    foreach(ColumnSchema column in SourceTable.NonForeignKeyColumns)
    {          
        temp += "if(columnNames.Contains(\""+ GetPascalName(column.Name) +"\"))"+"\r\n\t\t\t\t\t\t";
        if(GetCSharpVariableType(column) == "string")
        {
            temp += className + "." + GetPascalName(column.Name) + " = reader[\""+ GetPascalName(column.Name) +"\"].ToString();\r\n\t\t\t\t\t";
        }
        else
        {
            temp += className + "." + GetPascalName(column.Name) + " = ("+ GetCSharpVariableType(column) +")reader[\""+ GetPascalName(column.Name) +"\"];\r\n\t\t\t\t\t";    
        }                
    }
    return temp;
}
/*=============================*/
public string GetForeignKeyTableNewObjectText(TableSchema SourceTable,ColumnSchema columnName)
{
    string className = GetClassName(SourceTable);
    string temp = "";
    temp += className + " " + GetCamelName(className) + GetForeignKeyColumnName(columnName) + " = new " + className + "();";        
    return temp;
}
public string GetForeignKeyColumnsText(TableSchema SourceTable,ColumnSchema columnName)//SourceTable=????????
{    
    string className = GetClassName(SourceTable);
    string temp = "";
    int i=0;
    temp += ""+"if(columnNames.Contains(\""+ /*column*/columnName.Name +"\"))\r\n" + "\t\t\t\t\t{\r\n\t\t\t\t\t\t" 
            + GetCamelName(className) + GetForeignKeyColumnName(columnName) + "." + SourceTable.Columns[0].Name + " = (" + GetCSharpVariableType(/*column*/columnName)
            + ")reader[\""+ /*column*/columnName.Name +"\"];" + "\r\n\t\t\t\t\t}\r\n\t\t\t\t\t";
    foreach(ColumnSchema column in SourceTable.Columns)
    {
        if(i!=0)
        {
        temp += ""+"if(columnNames.Contains(\""+ column.Name +"\"))\r\n" + "\t\t\t\t\t{\r\n\t\t\t\t\t\t" 
            + GetCamelName(className) + GetForeignKeyColumnName(columnName) + "." + column.Name + " = (" + GetCSharpVariableType(column)
            + ")reader[\""+ column.Name +"\"];" + "\r\n\t\t\t\t\t}\r\n\t\t\t\t\t";
        }
        i++;
    }
    return temp;
}
public string AddForeignKeyObjectInPrimaryObject(TableSchema SourceTableForeign,ColumnSchema columnName)
{
    string className = GetClassName(SourceTableForeign);
    return GetCamelName(GetClassName(SourceTable)) + "." + GetPascalName(GetForeignKeyColumnName(columnName)) + " = " + GetCamelName(className) + GetForeignKeyColumnName(columnName) + ";\r\n";
}
public override string GetFileName()
{
    return this.GetClassName(this.SourceTable) + "Service.cs";
}
</script>

  BLL.cst(Business Logical Layer,对应于DAL层的每一个方法,起到调用DAL层的作用)

BLL

<%@ CodeTemplate Language="C#" TargetLanguage="C#" Description="Create:Teacher Pan"%>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="Context" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using MODEL;
using DAL;

namespace BLL
{
    public class <%=MakeSingle(SourceTable.Name)%>Manager
    {
        public static int Add<%=MakeSingle(SourceTable.Name)%>(<%=MakeSingle(SourceTable.Name)%> <%=GetCamelName(MakeSingle(SourceTable.Name))%>)
        {
            return <%=MakeSingle(SourceTable.Name)%>Service.Add<%=MakeSingle(SourceTable.Name)%>(<%=GetCamelName(MakeSingle(SourceTable.Name))%>);
        }
        public static int Update<%=MakeSingle(SourceTable.Name)%>(<%=MakeSingle(SourceTable.Name)%> <%=GetCamelName(MakeSingle(SourceTable.Name))%>)
        {
            return <%=MakeSingle(SourceTable.Name)%>Service.Update<%=MakeSingle(SourceTable.Name)%>(<%=GetCamelName(MakeSingle(SourceTable.Name))%>);
        }
        public static int Delete<%=MakeSingle(SourceTable.Name)%>(<%=GetCSharpVariableType(SourceTable.PrimaryKey.MemberColumns[0].Column)%> id)
        {
            return <%=MakeSingle(SourceTable.Name)%>Service.Delete<%=MakeSingle(SourceTable.Name)%>ById(id);
        }
        public static List<<%=MakeSingle(SourceTable.Name)%>> GetAll<%=SourceTable.Name%>()
        {
            return <%=MakeSingle(SourceTable.Name)%>Service.GetAll<%=SourceTable.Name%>();
        }
        public static <%=MakeSingle(SourceTable.Name)%> Get<%=MakeSingle(SourceTable.Name)%>ById(<%=GetCSharpVariableType(SourceTable.PrimaryKey.MemberColumns[0].Column)%> id)
        {
            return <%=MakeSingle(SourceTable.Name)%>Service.Get<%=MakeSingle(SourceTable.Name)%>ById(id);
        }
    }
}
<script runat="template">
public string GetCSharpVariableType(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 MakeSingle(string name)
{
    return name;
}
public string GetCamelName(string name)
{
    return name.Substring(0,1).ToLower() + name.Substring(1);
}
public override string GetFileName()
{
    return this.MakeSingle(this.SourceTable.Name) + "Manager.cs";
}
</script>

  

将上述三个源文件按对应文件名保存,然后用CodeSmith Studio打开即可使用。

打开一个源文件,如MODEL.cst,在属性窗口【Properties】中,我们会看到【SourceTable】,点击旁边的按钮,选择对应的表。然后按【F5】,或者菜单栏的【run】,即可生成我们需要的代码,每一个表对用生成MODEL、DAL、BLL三个代码,名字分别为 TableName.cs、TableNameServices.cs、TableNameManager.cs。生成第一个类之后马上执行下一步操作。

4.在Visual Studio中生成项目

新建项目,选择【其他项目类型】中的【Visual Studio解决方案】,假如解决方案取名为TestCS,路径为“D:\”。

在【解决方案管理器】中找到刚新建的解决方案,右键【添加】,【新建项目】,【类库】。创建名为MODEL、DAL、BLL的三个类库。将CodeSmith中生成的代码分别考到对应的项目文件夹中,在解决方案中添加好。

继续右键右键【添加】,【新建网站】。注意路径应浏览到刚新建项目的对应文件夹下 ,此例中为“D:\TestCS\WEB”,点击【确定】,如果提示目录不存在,需要创建,则创建。这样就可以保证三个类库和网站都在同一个目录下。

 

5.添加引用

右键【DAL】,【添加引用...】,在弹出的【添加引用】对话框中,切换到【项目】选项卡,选择MODEL,确定。接下来分别为【BLL】添加MODEL、DAL引用,为【WEB】添加MODEL、DAL、BLL引用。

 

6.启动项设置

右键【WEB】,【设为启动项目】。

至此,此项目的解决方案构架基本完成。

 

总结:这个构架总的来说还是,比较简单的项目,使用使用它还是比较方便的,需要添加方法也可以直接在对应的类中编写。如果编码过程中数据库表还有改动的话,这将是比较麻烦的事,因为MODEL、DAL两层的代码都要改变。另外,我还用过一种构架,动软代码生成器。它比较强大,甚至可以生成整个项目,可是我嫌它太过于庞大,比较适合大型项目。另一个原因就是第一次接触的就是CodeSmith,适合了它的模式,习惯啊习惯!

 

运用CodeSmith Studio实现C#项目构架

上一篇:在C#中mongohelper的初始化


下一篇:转 Datatables中文API——基本参数