滑兔

博客园 首页 新随笔 联系 订阅 管理

利用CodeSmith从数据库中的相关表格生成业务逻辑层的具体业务对象,网络上已经有很多,而CodeSmith中也提供了几个,但个人觉得不适合我的项目,我自己写了个生成模板,有兴趣的朋友可以下载试用。模板生成的代码中的数据处理部分(即DataAccess的),请朋友们改成自己的数据处理方法。
有任何建议请留言,或E-Mail:Cairabbit@126.com。谢谢!
TableObject.cst的原代码如下:
<%--
Name:
Author: CCS
Description:
--%>
<%@ CodeTemplate Language="C#" TargetLanguage="C#" Src="TableObject.cst.cs" Inherits="CodeSmith.MyTemplates.TableObjectTemplate" Description="Generate A DataTable Collection and Persis object." %>
<%@ Property Name="SourceTable" Type="SchemaExplorer.TableSchema" Category="Context" Description="Table that the object is based on." %>
<%@ Property Name="Company" Type="System.String" Default="CCS" Optional="True" Category="Strings" Description="Set the class namespace" %>
<%@ Assembly Name="SchemaExplorer" %>
<%@ Assembly Name="System.Data" %>
<%@ Import Namespace="SchemaExplorer" %>
<%@ Import Namespace="System.Data" %>
/* ********************************************************************************
 * 名称:
 * 描述:数据库表格 <%= SourceTable.Name %> 的集合类、实体类、枚举类
 *
 * 创建人:
 * 创建日期:<%= System.DateTime.Today.ToString("yyyy-MM-dd") %>
 * 修改人:
 * 修改日期:
 * *******************************************************************************/
using System;
using System.Data;
using System.Collections;
using MELWrapper.Data;

namespace <%= Company %>.BizRules
{
 /// <summary>
 /// 数据库表格 <%= SourceTable.Name %> 的集合类 <%= GetClassName(SourceTable) %>Collection
 /// </summary>
 [Serializable()]
 public class <%= GetClassName(SourceTable) %>Collection : IBizObject
 {
  #region 变量定义
  
  private DataTable table = null;
 
  #endregion
  
  #region 构造函数
  
  /// <summary>
  /// 构造函数
  /// </summary>
  public <%= GetClassName(SourceTable) %>Collection()
  {
   InitTable();
  }
  
  #endregion
  
  #region 方法
   
  /// <summary>
  /// 初始化表格对象
  /// </summary>
  public void InitTable()
  {
   <% if (SourceTable.PrimaryKey.MemberColumns.Count <= 0) { throw new Exception("Table Has NO Key Columns!"); } %>
   table = new DataTable("<%= SourceTable.Name %>");
   
   <% for (int i = 0; i < SourceTable.Columns.Count; i++) { %>
   DataColumn col<%= SourceTable.Columns[i].Name %> = new DataColumn("<%= SourceTable.Columns[i].Name %>", typeof(<%= GetCSharpVariableType(SourceTable.Columns[i]) %>), "", MappingType.Element);
   col<%= SourceTable.Columns[i].Name %>.AllowDBNull = <% if (SourceTable.Columns[i].AllowDBNull) { %>true<% } else { %>false<% } %>;
   col<%= SourceTable.Columns[i].Name %>.Caption = "<%= GetSpacedName(SourceTable.Columns[i].Name) %>";
   <% if (SizeMatters(SourceTable.Columns[i])) { %>
   col<%= SourceTable.Columns[i].Name %>.MaxLength = <%= SourceTable.Columns[i].Size %>;
   <% } %>
   col<%= SourceTable.Columns[i].Name %>.Unique = <% if (SourceTable.PrimaryKey.MemberColumns.Count == 1 && SourceTable.Columns[i].IsPrimaryKeyMember) { %>true<% } else { %>false<% } %>;
   col<%= SourceTable.Columns[i].Name %>.DefaultValue = Convert.DBNull;
   col<%= SourceTable.Columns[i].Name %>.ExtendedProperties.Add("IsKey", "<% if (SourceTable.Columns[i].IsPrimaryKeyMember) { %>true<% } else { %>false<% } %>");
   col<%= SourceTable.Columns[i].Name %>.ExtendedProperties.Add("ReadOnly", "false");
   col<%= SourceTable.Columns[i].Name %>.ExtendedProperties.Add("Description", "<%= GetSpacedName(SourceTable.Columns[i].Name) %>");
   <% if (SizeMatters(SourceTable.Columns[i])) { %>
   col<%= SourceTable.Columns[i].Name %>.ExtendedProperties.Add("Length", "<%= SourceTable.Columns[i].Size %>");
   <% } %>
   col<%= SourceTable.Columns[i].Name %>.ExtendedProperties.Add("Decimals", "0");
   col<%= SourceTable.Columns[i].Name %>.ExtendedProperties.Add("AllowDBNulls", "<% if (SourceTable.Columns[i].AllowDBNull) { %>true<% } else { %>false<% } %>");
   table.Columns.Add(col<%= SourceTable.Columns[i].Name %>);
   
   <% } %>
   <% if (SourceTable.PrimaryKey.MemberColumns.Count >= 1) { %>
   table.PrimaryKey = new DataColumn[] {<%= GetKeyColumnVariable(SourceTable) %>};
   <% } %>
  }
  
  /// <summary>
  /// 集合中是否包括有<%= GetClassName(SourceTable) %>对象
  /// </summary>
  /// <param name="obj"><%= GetClassName(SourceTable) %>对象</param>
  /// <returns>包含该对象返回true;否则为false</returns>
  public bool Contains(<%= GetClassName(SourceTable) %> obj)
  {
   bool contains = false;
   if( table != null )
   {
    object[] keys = new object[]{<%= GetObjectKeyColumnVariable(SourceTable) %>};
    contains = table.Rows.Contains(keys);
   }
   return contains;
  }
  
  /// <summary>
  /// 通过主键获取<%= GetClassName(SourceTable) %>对象
  /// </summary>
  /// <returns>返回<%= GetClassName(SourceTable) %>对象</returns>
  public <%= GetClassName(SourceTable) %> Get<%= GetClassName(SourceTable) %>(<%= GetKeyDeclaration(SourceTable) %>)
  {
   if( table != null )
   {
    object[] keys = new object[]{<%= GetKeyVariable(SourceTable) %>};
    DataRow row = table.Rows.Find(keys);
    if( row != null )
    {
     <%= GetClassName(SourceTable) %> obj = new <%= GetClassName(SourceTable) %>(<%= GetKeyRowConvert(SourceTable) %>);
     obj.FromDataRow(row);
     return obj;
    }
   }
   return null;
  }
  
  /// <summary>
  /// 更新集合中的<%= GetClassName(SourceTable) %>对象,如果该对象不存在,则抛出异常
  /// </summary>
  /// <param name="obj"><%= GetClassName(SourceTable) %>对象</param>
  public void Update<%= GetClassName(SourceTable) %>(<%= GetClassName(SourceTable) %> obj)
  {
   object[] keys = new object[]{<%= GetObjectKeyColumnVariable(SourceTable) %>};
   DataRow row = table.Rows.Find(keys);
   if( row != null )
   {
    obj.ToDataRow(ref row);
   }
   else
   {
    throw new NullReferenceException();
   }
  }
  
  /// <summary>
  /// 将<%= GetClassName(SourceTable) %>对象加入集合,如果已经存在,则更新该对象。
  /// </summary>
  /// <param name="obj"><%= GetClassName(SourceTable) %>对象</param>
  public void Add(<%= GetClassName(SourceTable) %> obj)
  {
   if(Contains(obj))
   {
    Update<%= GetClassName(SourceTable) %>(obj);
   }
   else
   {
    DataRow row = table.NewRow();
    obj.ToDataRow(ref row);
    table.Rows.Add(row);
   }
  }
  
  /// <summary>
  /// 从集合中移除<%= GetClassName(SourceTable) %>对象,如果对象不存在,则抛出异常
  /// </summary>
  /// <param name="obj"></param>
  public void Remove(<%= GetClassName(SourceTable) %> obj)
  {
   object[] keys = new object[]{<%= GetObjectKeyColumnVariable(SourceTable) %>};
   DataRow row = table.Rows.Find(keys);
   if( row != null )
   {
    row.Delete();
   }
   else
   {
    throw new NullReferenceException();
   }
  }
  
  /// <summary>
  /// 从集合中移除第N个对象,如果不存在,则抛出异常
  /// </summary>
  /// <param name="index">第N个</param>
  public void Remove(int index)
  {
   if( index < 0 || index > table.Rows.Count - 1 )
    throw new NullReferenceException();

   DataRow row = table.Rows[index];
   if( row != null )
   {
    row.Delete();
   }
  }
  
  /// <summary>
  /// 根据过滤条件,从集合中获取相应的 <%= GetClassName(SourceTable) %>对象数组
  /// </summary>
  /// <param name="filter">根据过滤条件</param>
  /// <returns> <%= GetClassName(SourceTable) %>对象</returns>
  public <%= GetClassName(SourceTable) %>[] Select(string filter)
  {
   DataRow[] rows = table.Select(filter);
   if( rows != null && rows.Length > 0 )
   {
    <%= GetClassName(SourceTable) %>[] objs = new <%= GetClassName(SourceTable) %>[rows.Length];
    for( int i=0; i < rows.Length; i++ )
    {
     DataRow row = rows[i];
     <%= GetClassName(SourceTable) %> obj = new <%= GetClassName(SourceTable) %>(<%= GetKeyRowConvert(SourceTable) %>);
     obj.FromDataRow(row);
     objs[i] = obj;
    }
    return objs;
   }
   return null;
  }
  
  /// <summary>
  /// 移除集合中所有对象,并可更新到数据库中
  /// </summary>
  public void RemoveAll()
  {
   if( table != null )
   {
    foreach(DataRow row in table.Rows)
     row.Delete();
   }
  }
  
  /// <summary>
  /// 清楚集合中的所有对象,但不可更新到数据库中
  /// </summary>
  public void Clear()
  {
   if( table != null )
   {
    table.Rows.Clear();
   }
  }
  
  /// <summary>
  /// 载入数据库中的所有该业务对象
  /// </summary>
  public void Load()
  {
   DataAccess da = new DataAccess();
   DataSet ds = new DataSet();
   ds.Tables.Add(table);
   da.LoadDataSet(ds,table.TableName);
   ds.Tables.Remove(table);
   ds.Dispose();
  }
  
  /// <summary>
  /// 根据过滤条件,载入数据库中的对象集合
  /// </summary>
  /// <param name="filter">过滤条件</param>
  public void Load(string filter)
  {
   DataAccess da = new DataAccess();
   DataSet ds = new DataSet();
   ds.Tables.Add(table);
   string sql = string.Format("SELECT * FROM <%= SourceTable.Name %> WHERE 1=1{0}",filter == "" ? "" : " AND " + filter);
   DataSet tempDs = da.ExecuteDataSet(CommandType.Text,sql);
   tempDs.Tables[0].TableName = table.TableName;
   ds.Merge(tempDs);
   ds.Tables.Remove(table);
   tempDs.Dispose();
   ds.Dispose();
  }
  
  /// <summary>
  /// 保存集合中的所有修改至数据库中
  /// </summary>
  public void Save()
  {
   DataSet ds = new DataSet();
   ds.Tables.Add(table.Copy());
   if( ds.HasChanges() )
   {
    DataAccess da = new DataAccess();
    da.UpdateDataSet(ds.GetChanges());
    table.AcceptChanges();
   }
  }
  
  /// <summary>
  /// 获取当前集合中第N个对象
  /// </summary>
  public <%= GetClassName(SourceTable) %> this[int index]
  {
   get
   {
    DataRow row = Source.Rows[index];
    if( row != null )
    {
     <%= GetClassName(SourceTable) %> obj = new <%= GetClassName(SourceTable) %>(<%= GetKeyRowConvert(SourceTable) %>);
     obj.FromDataRow(row);
     return obj;
    }
    return null;
   }
  }
     
  /// <summary>
  /// 复制对象至数据中
  /// </summary>
  public void CopyTo(Array array, int index)
  {
   <%= GetClassName(SourceTable) %>[] objs = new <%= GetClassName(SourceTable) %>[this.Count];
   for(int i=0; i<this.Count; i++)
    objs[i] = this[i];
   Array.Copy(objs,0,array,index,this.Count);
  }

  /// <summary>
  /// 获取集合的枚举类
  /// </summary>
  /// <returns>集合的枚举类</returns>
  public IEnumerator GetEnumerator()
  {
   return new <%= GetClassName(SourceTable) %>Enumerator(this);
  }
   
  #endregion
  
  #region 属性
   
  /// <summary>
  /// 集合中对象个数
  /// </summary>
  public int Count
  {
   get
   {
    if( table == null )
     return 0;
    return table.Rows.Count;
   }
  }
  
  public bool IsSynchronized
  {
   get
   {
    return false;
   }
  }
  
  public object SyncRoot
  {
   get
   {
    return null;
   }
  }

  /// <summary>
  /// 集合的数据库源表格
  /// </summary>
  public DataTable Source
  {
   get
   {
    return table;
   }
  }
  
  /// <summary>
  /// 集合的名称
  /// </summary>
  public string Name
  {
   get
   {
    return "<%= SourceTable.Name %>";
   }
  }

  
  /// <summary>
  /// 该<%= SourceTable.Name %>对象是否保存于缓存中
  /// </summary>
  public bool IsCached
  {
   get
   {
    return false;
   }
  }

  #endregion
 }

 /// <summary>
 /// 数据库表格 <%= SourceTable.Name %> 的实体类 <%= GetClassName(SourceTable) %>
 /// </summary>
 [Serializable()]
 public class <%= GetClassName(SourceTable) %>
 {
  #region 变量定义
  
  #region 主键
  
  <% foreach(ColumnSchema column in SourceTable.PrimaryKey.MemberColumns) { %>
  <%= GetMemberVariableDeclarationStatement(column) %>
  <% } %>

  #endregion

  <% foreach (ColumnSchema column in SourceTable.NonPrimaryKeyColumns) { %>
  <%= GetMemberVariableDeclarationStatement(column) %>
  <% } %>

  #endregion
  
  #region 构造函数
  
  /// <summary>
  /// 构造函数
  /// </summary>
  public <%= GetClassName(SourceTable) %>()
  {
  <% foreach(ColumnSchema column in SourceTable.PrimaryKey.MemberColumns) { %>
   <%= GetMemberVariableName(column)%> = <%= GetMemberVariableInitialValue(column) %>;
  <% } %>
  }
  
  /// <summary>
  /// 构造函数
  /// </summary>
  public <%= GetClassName(SourceTable) %>(<%= GetKeyDeclaration(SourceTable) %>)
  {
  <% foreach(ColumnSchema column in SourceTable.PrimaryKey.MemberColumns) { %>
   this.<%= GetMemberVariableName(column)%> = <%= GetMemberVariableName(column) %>;
  <% } %>
  }
  
  #endregion
  
  #region 方法
  
  /// <summary>
  /// 从数据库源的记录行设置对象属性
  /// </summary>
  /// <param name="row">记录行</param>
  internal void FromDataRow(DataRow row)
  {
   bool isCurrent = false;
  <% for (int i=0;i<SourceTable.PrimaryKey.MemberColumns.Count;i++) { %>
   isCurrent = <% if(i>0){%>isCurrent && <%}%> this.<%= GetMemberVariableName(SourceTable.PrimaryKey.MemberColumns[i])%> == <%= GetCSharpConvert(SourceTable.PrimaryKey.MemberColumns[i]) %>;
  <% } %>
   if( !isCurrent )
    throw new NullReferenceException();
  <% foreach (ColumnSchema column in SourceTable.NonPrimaryKeyColumns) { %>
   this.<%= GetPropertyName(column) %> = <%= GetCSharpConvert(column) %>;
  <% } %>
  }
  
  /// <summary>
  /// 将对象的属性设置到引用的记录行
  /// </summary>
  /// <param name="row">记录行</param>
  internal void ToDataRow(ref DataRow row)
  {
   <% foreach (ColumnSchema column in SourceTable.Columns) { %>
   row["<%= GetPropertyName(column) %>"] = this.<%= GetPropertyName(column) %>;
   <% } %>
  }
  
  #endregion
  
  #region 属性
  
  #region 主键
  
  <% foreach(ColumnSchema column in SourceTable.PrimaryKey.MemberColumns) { %>
  /// <summary>
  /// 属性<%= GetPropertyName(column) %>
  /// </summary>
  public <%= GetCSharpVariableType(column) %> <%= GetPropertyName(column) %>
  {
   get {return <%=GetMemberVariableName(column) %>;}
  }
  <% } %>
  
  #endregion
  
  <% for (int i = 0; i < SourceTable.NonPrimaryKeyColumns.Count; i++) { %>
  /// <summary>
  /// 属性<%= GetPropertyName(SourceTable.NonPrimaryKeyColumns[i]) %>
  /// </summary>
  public <%= GetCSharpVariableType(SourceTable.NonPrimaryKeyColumns[i]) %> <%= GetPropertyName(SourceTable.NonPrimaryKeyColumns[i]) %>
  {
   get {return <%= GetMemberVariableName(SourceTable.NonPrimaryKeyColumns[i]) %>;}
   set {<%= GetMemberVariableName(SourceTable.NonPrimaryKeyColumns[i]) %> = value;}
  }
  <% if (i < SourceTable.NonPrimaryKeyColumns.Count - 1) Response.Write("\r\n"); %>  
  <% } %>
  
  #endregion
 }
 
 /// <summary>
 /// 数据库表格 <%= SourceTable.Name %> 的枚举类 <%= GetClassName(SourceTable) %>
 /// </summary>
 public class <%= GetClassName(SourceTable) %>Enumerator : IEnumerator
 {
  private int position = -1;
  private <%= GetClassName(SourceTable) %>Collection colObj;

  /// <summary>
  /// 构造函数
  /// </summary>
  public <%= GetClassName(SourceTable) %>Enumerator(<%= GetClassName(SourceTable) %>Collection colObj)
  {
   this.colObj = colObj;
  }

  #region IEnumerator 成员

  /// <summary>
  /// 重置枚举位置为-1
  /// </summary>
  public void Reset()
  {
   position = -1;
  }

  /// <summary>
  /// 获取枚举中的当前对象
  /// </summary>
  public object Current
  {
   get
   {
    if( position < 0 || position > colObj.Source.Rows.Count - 1 )
     return null;

    DataRow row = colObj.Source.Rows[position];

    while( row != null && (row.RowState == DataRowState.Deleted || row.RowState == DataRowState.Detached) )
    {
     position ++;
     if( position > colObj.Source.Rows.Count - 1 )
     {
      row = null;
      break;
     }
     row = colObj.Source.Rows[position];
    }
    if( row != null )
    {
     Customer obj = new Customer(Convert.ToString(row["CustomerID"]));
     obj.FromDataRow(row);
     return obj;
    }
    return null;
   }
  }

  /// <summary>
  /// 设置枚举的当前位置加1,并返回是否存在下一个枚举对象
  /// </summary>
  public bool MoveNext()
  {
   position ++;
   if( position > colObj.Source.Rows.Count - 1 )
    return false;

   DataRow row = colObj.Source.Rows[position];

   while( row != null && (row.RowState == DataRowState.Deleted || row.RowState == DataRowState.Detached) )
   {
    position ++;
    if( position > colObj.Source.Rows.Count - 1 )
    {
     row = null;
     break;
    }
    row = colObj.Source.Rows[position];
   }
   return row != null;
  }

  #endregion

 }
}

相应的TableObject.cst.cs代码如下:
using System;
using System.Text;
using System.Data;
using CodeSmith.Engine;
using SchemaExplorer;

namespace CodeSmith.MyTemplates
{
 public class TableObjectTemplate : CodeTemplate
 {
  public string GetKeyDeclaration(TableSchema table)
  {
   string str = "";
   foreach(ColumnSchema column in table.PrimaryKey.MemberColumns)
   {
    str += GetCSharpVariableType(column) + " " + GetMemberVariableName(column) + ",";
   }
   return str.TrimEnd(',');
  }
  
  public string GetKeyVariable(TableSchema table)
  {
   string str = "";
   foreach(ColumnSchema column in table.PrimaryKey.MemberColumns)
   {
    str += GetMemberVariableName(column) + ",";
   }
   return str.TrimEnd(',');
  }
  
  public string GetObjectKeyColumnVariable(TableSchema table)
  {
   string str = "";
   foreach(ColumnSchema column in table.PrimaryKey.MemberColumns)
   {
    str += "obj." + GetPropertyName(column) + ",";
   }
   return str.TrimEnd(',');
  }
  
  public string GetKeyColumnVariable(TableSchema table)
  {
   string str = "";
   foreach(ColumnSchema column in table.PrimaryKey.MemberColumns)
   {
    str += "col" + GetPropertyName(column) + ",";
   }
   return str.TrimEnd(',');
  }
  
  public string GetKeyRowConvert(TableSchema table)
  {
   string str = "";
   foreach(ColumnSchema column in table.PrimaryKey.MemberColumns)
   {
    str += GetCSharpConvert(column) + ",";
   }
   return str.TrimEnd(',');
  }
  
  public string GetMemberVariableDeclarationStatement(ColumnSchema column)
  {
   return GetMemberVariableDeclarationStatement("protected", column);
  }
  public string GetMemberVariableDeclarationStatement(string protectionLevel, ColumnSchema column)
  {
   string statement = protectionLevel + " ";
   statement += GetCSharpVariableType(column) + " " + GetMemberVariableName(column);
   
   string defaultValue = GetMemberVariableDefaultValue(column);
   if (defaultValue != "")
   {
    statement += " = " + defaultValue;
   }
   
   statement += ";";
   
   return statement;
  }
  
  public string GetReaderAssignmentStatement(ColumnSchema column, int index)
  {
   string statement = "if (!reader.IsDBNull(" + index.ToString() + ")) ";
   statement += GetMemberVariableName(column) + " = ";
   
   if (column.Name.EndsWith("TypeCode")) statement += "(" + column.Name + ")";
   
   statement += "reader." + GetReaderMethod(column) + "(" + index.ToString() + ");";
   
   return statement;
  }
  
  public string GetCamelCaseName(string value)
  {
   return value.Substring(0, 1).ToLower() + value.Substring(1);
  }
  
  public string GetMemberVariableName(ColumnSchema column)
  {
   string propertyName = GetPropertyName(column);
   string memberVariableName = GetCamelCaseName(propertyName);
   
   return memberVariableName;
  }
  
  public string GetPropertyName(ColumnSchema column)
  {
   string propertyName = column.Name;
   
   if (propertyName == column.Table.Name + "Name") return "Name";
   if (propertyName == column.Table.Name + "Description") return "Description";
   
   if (propertyName.EndsWith("TypeCode")) propertyName = propertyName.Substring(0, propertyName.Length - 4);
   
   return propertyName;
  }
    
  public string GetMemberVariableDefaultValue(ColumnSchema column)
  {
   switch (column.DataType)
   {
    case DbType.Guid:
    {
     return "System.Guid.Empty";
    }
    case DbType.AnsiString:
    case DbType.AnsiStringFixedLength:
    case DbType.String:
    case DbType.StringFixedLength:
    {
     return "String.Empty";
    }
    default:
    {
     return "";
    }
   }
  }
  
  public string GetMemberVariableInitialValue(ColumnSchema column)
  {
   switch (column.DataType)
   {
    case DbType.Guid:
    {
     return "System.Guid.NewGuid()";
    }
    case DbType.AnsiString:
    case DbType.AnsiStringFixedLength:
    case DbType.String:
    case DbType.StringFixedLength:
    {
     return "String.Empty";
    }
    default:
    {
     return "";
    }
   }
  }
  
  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 string GetCSharpConvert(ColumnSchema column)
  {
   if (column.Name.EndsWith("TypeCode")) return "(" + column.Name + ")row[\"" + column.Name + "\"]";
   
   switch (column.DataType)
   {
    case DbType.AnsiString: return "Convert.ToString(row[\"" + column.Name + "\"])";
    case DbType.AnsiStringFixedLength: return "Convert.ToString(row[\"" + column.Name + "\"])";
    case DbType.Binary: return "(byte[])row[\"" + column.Name + "\"]";
    case DbType.Boolean: return "Convert.ToBoolean(row[\"" + column.Name + "\"])";
    case DbType.Byte: return "Convert.ToByte(row[\"" + column.Name + "\"])";
    case DbType.Currency: return "Convert.ToDecimal(row[\"" + column.Name + "\"])";
    case DbType.Date: return "Convert.DateTime(row[\"" + column.Name + "\"])";
    case DbType.DateTime: return "Convert.DateTime(row[\"" + column.Name + "\"])";
    case DbType.Decimal: return "Convert.Decimal(row[\"" + column.Name + "\"])";
    case DbType.Double: return "Convert.Double(row[\"" + column.Name + "\"])";
    case DbType.Guid: return "(Guid)row[\"" + column.Name + "\"]";
    case DbType.Int16: return "(short)row[\"" + column.Name + "\"]";
    case DbType.Int32: return "Convert.ToInt32(row[\"" + column.Name + "\"])";
    case DbType.Int64: return "(long)row[\"" + column.Name + "\"]";
    case DbType.Object: return "row[\"" + column.Name + "\"]";
    case DbType.SByte: return "Convert.ToSByte(row[\"" + column.Name + "\"])";
    case DbType.Single: return "(float)row[\"" + column.Name + "\"]";
    case DbType.String: return "Convert.ToString(row[\"" + column.Name + "\"])";
    case DbType.StringFixedLength: return "Convert.ToString(row[\"" + column.Name + "\"])";
    case DbType.Time: return "(TimeSpan)row[\"" + column.Name + "\"]";
    case DbType.UInt16: return "(ushort)row[\"" + column.Name + "\"]";
    case DbType.UInt32: return "Convert.ToUInt32(row[\"" + column.Name + "\"])";
    case DbType.UInt64: return "(ulong)row[\"" + column.Name + "\"]";
    case DbType.VarNumeric: return "Convert.ToDecimal(row[\"" + column.Name + "\"])";
    default:
    {
     return "row[\"" + column.Name + "\"]";
    }
   }
  }
  
  public string GetReaderMethod(ColumnSchema column)
  {
   switch (column.DataType)
   {
    case DbType.Byte:
    {
     return "GetByte";
    }
    case DbType.Int16:
    {
     return "GetInt16";
    }
    case DbType.Int32:
    {
     return "GetInt32";
    }
    case DbType.Int64:
    {
     return "GetInt64";
    }
    case DbType.AnsiStringFixedLength:
    case DbType.AnsiString:
    case DbType.String:
    case DbType.StringFixedLength:
    {
     return "GetString";
    }
    case DbType.Boolean:
    {
     return "GetBoolean";
    }
    case DbType.Guid:
    {
     return "GetGuid";
    }
    case DbType.Currency:
    case DbType.Decimal:
    {
     return "GetDecimal";
    }
    case DbType.DateTime:
    case DbType.Date:
    {
     return "GetDateTime";
    }
    case DbType.Binary:
    {
     return "GetBytes";
    }
    default:
    {
     return "__SQL__" + column.DataType;
    }
   }
  }
  
  public string GetClassName(TableSchema table)
  {
   int i = table.Name.IndexOf("_")+1;
   if( table.Name.EndsWith("ies") )
   {
    return table.Name.Substring(i, table.Name.Length - 3) + "y";
   }
   else if (table.Name.EndsWith("s"))
   {
    return table.Name.Substring(i, table.Name.Length - 1);
   }
   else
   {
    return table.Name.Substring(i, table.Name.Length - i);;
   }
  }
  
  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";
    default: return "__UNKNOWN__" + column.NativeType;
   }
  }
  
  public string GetSpacedName(string value)
  {
   StringBuilder spacedName = new StringBuilder();
   
   for (int i = 0; i < value.Length; i++)
   {
    if (i > 0 && i < value.Length - 1 && value.Substring(i, 1).ToUpper() == value.Substring(i, 1))
    {
     spacedName.Append(" ");
    }
    spacedName.Append(value[i]);
   }
   
   return spacedName.ToString();
  }
  
  public bool SizeMatters(ColumnSchema column)
  {
   switch (column.DataType)
   {
    case DbType.String:
    case DbType.AnsiString:
    case DbType.AnsiStringFixedLength:
    case DbType.Decimal:
    {
     return true;
    }
    default:
    {
     return false;
    }
   }
  }
 }
}

posted on 2005-11-10 16:35  sneak  阅读(3458)  评论(3)    收藏  举报