代码生成器,写好了一个Ibatis.Net的模板
<%#NAMESPACE System.IO, System.Text, System.Text.RegularExpressions, System.Globalization %><%
// $Id: CSharp_IBatis_BusinessObject.csgen,v 1.3 2005/12/15 23:57:34 morciuch Exp $
public class GeneratedTemplate : DotNetScriptTemplate
{
//选中的表
private IList _selectedTables;
//数据库名
private string _dbName;
//表名
private string _tableName;
//当前处理的表
private ITable _workingTable;
//类名
private string _className;
private string _beanName;
//输出路径
private string _exportPath;
//文件名
private string _fileName;
//Top命名空间
private string _topNameSpace;
//BLL命名空间
private string _bllNameSpace;
//DAL命名空间
private string _dalNameSpace;
//Model命名空间
private string _modleNameSpace="Model";
//Help命名空间
private string _helpNameSpace;
//配置文件中的连接字符串名
private string _helpClassName;
//私有变量前缀
private string _prefix="_";
public GeneratedTemplate(ZeusContext context) : base(context) {}
//---------------------------------------------------
// Render() is where you want to write your logic
//---------------------------------------------------
public override void Render()
{
_dbName = input["chooseDatabase"].ToString();
_selectedTables = input["chooseTables"] as ArrayList;
_exportPath = input["outputPath"].ToString();
_topNameSpace = input["topNamespace"].ToString();
_bllNameSpace = input["bllNamespace"].ToString();
_dalNameSpace = input["dalNamespace"].ToString();
_helpNameSpace = input["helpNamespace"].ToString();
_helpClassName = input["helpClassName"].ToString();
ITables _allTables = MyMeta.Databases[_dbName].Tables;
foreach (Table _newTable in _allTables)
{
_workingTable = _newTable;
_tableName = _workingTable.Alias.Replace(" ", "");
if (IsSelect(_tableName))
{
_className = TableToClassName(_workingTable);
SetBeanName();
CreateModelFile(_workingTable.Columns);//生成当前表的Model类
GenerateDaoFile(_workingTable.Columns);//生成当前表的Dao类
GenerateMappingFile( _workingTable.Columns );//生成xml文件
}
}
System.Diagnostics.Process.Start("explorer.exe",_exportPath);//文件输出完毕,打开输出文件夹
}
#region 生成bean的方法--begin
private void CreateModelFile(IColumns Columns)
{
//实体头-begin
output.writeln("using System;");
output.writeln("using System.Text;");
output.writeln("using System.Data;");
output.writeln("using System.Collections;");
output.writeln("using System.Collections.Generic;");
output.writeln("");
output.writeln("/// <summary>");
output.writeln("///\tMyGeneration : 实体类 " + _className);
Version();
output.writeln("/// </summary>");
output.writeln("namespace " + _topNameSpace + "." + _modleNameSpace);
output.writeln("{");
output.writeln("[Serializable]");
output.writeln("\tpublic class " + _className+":DomainBase");
output.writeln("\t{");
//实体头-end
//默认构造函数-begin
output.writeln("\t\t#region 默认构造函数");
output.writeln("\t\tpublic " + _className + "()");
output.writeln("\t\t{");
output.writeln("\t\t}");
output.writeln("\t\t#endregion ");
output.writeln("");//换行
//默认构造函数-end
//私有成员变量-begin
if (Columns.Count > 0)
{
output.writeln("\t\t#region 私有成员");
foreach (IColumn field in Columns)
{
if (field.IsInPrimaryKey)
{
continue;
}
string fieldName = FirstToUpper(field.Name);
string cType = field.LanguageType;
output.write("\t\tprivate " + cType + " _" + fieldName + " ");
if (cType == "string")
{
output.writeln("=string.Empty;");//如果是string类型则赋值为string.Empty
}
else
{
output.writeln(";");//如果是非string类型则为默认的空值 null false 0
}
}
output.writeln("\t\t#endregion");
}
//私有成员变量-end
//对外公开的属性-begin
if (Columns.Count > 0)
{
output.writeln("");
output.writeln("\t\t#region 公有属性");
//全部属性
foreach (IColumn Column in Columns)
{
if (Column.IsInPrimaryKey)
{
continue;
}
output.writeln("");
output.writeln("\t\t/// <summary>");
output.writeln("\t\t///" + Column.Description + "");
output.writeln("\t\t/// </summary>");
string fieldName = FirstToUpper(Column.Name);
string fieldType = Column.LanguageType;
output.writeln("\t\tpublic " + fieldType + " " + fieldName);
output.writeln("\t\t{");
output.writeln("\t\t\tget { return _" + fieldName + "; }");
output.writeln("\t\t\tset { _" + fieldName + " = value; }");
output.writeln("\t\t}");
}
output.writeln("\t\t#endregion ");
}
//对外公开的属性-end
//实体尾-begin
output.writeln("\t}");
output.writeln("}");
_fileName = _className + ".cs";
output.saveEnc(_exportPath + "\\" + _modleNameSpace + "\\" + _fileName, "o", "unicode");
output.clear();
//实体尾-end
}
#endregion
private void GenerateDaoFile( IColumns Columns )
{
output.writeln( "using System;");
output.writeln( "using System.Collections.Generic;");
output.writeln( "using System.Text;");
output.writeln("using " + _topNameSpace + "." + _modleNameSpace+";" );
output.writeln( "");
output.writeln("");
output.writeln("/// <summary>");
output.writeln("///\tMyGeneration : 实体类 " + _className);
Version();
output.writeln("/// </summary>");
output.writeln("namespace " + _topNameSpace + "." + _dalNameSpace );
output.writeln( "{");
output.writeln("\tpublic class " + _className+"Dao:DaoBase<"+_className+">");
output.writeln( " {");
output.writeln( " public override string SqlMapNamespace");
output.writeln( " {");
output.writeln( " get { return \""+_className+"\"; }");
output.writeln( " }");
output.writeln( " }");
output.writeln( "}");
_fileName = _className + "Dao.cs";
output.saveEnc(_exportPath + "\\" + _dalNameSpace + "\\" + _fileName, "o", "unicode");
output.clear();
}
private void GenerateMappingFile( IColumns Columns )
{
if( Columns.Count > 0 )
{
output.writeln( "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" );
output.writeln( "<sqlMap namespace=\"" + _className + "\" " );
output.writeln("\t\t\t xmlns=\"http://ibatis.apache.org/mapping/"");
output.writeln("\t\t\t xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance/">");
output.writeln( "<alias>" );
output.writeln( "\t" + IBatisAliasTag());
output.writeln( "</alias>" );
output.writeln( "<resultMaps>" );
output.writeln( "\t\t" + IBatisResultMap( Columns ) );
output.writeln( "</resultMaps>" );
output.writeln( "<statements>" );
IBatisStatements( Columns );
output.writeln( "</statements>" );
output.writeln( "</sqlMap>" );
}
_fileName = _className + ".xml";
output.saveEnc(_exportPath + "http://www.cnblogs.com/xrt2004/admin/file://mapping//" + _fileName, "o", "unicode");
output.clear();
}
private string IBatisAliasTag()
{
object[] args = {_className, _topNameSpace+"."+_modleNameSpace+"."+_className,_topNameSpace};
return string.Format("<typeAlias alias=\"{0}\" type=\"{1},{2}\" />", args);
}
private string IBatisResultMap( IColumns Columns )
{
StringBuilder xml = new StringBuilder();
object[] args = {_className, _className};
xml.AppendLine(string.Format("<resultMap id=\"{0}Result\" class=\"{1}\">", args));
foreach( IColumn c in Columns )
{
object[] args1 = {
FirstToUpper(c.Name),
c.Name,
CLRTypeToIBatisType(c),
CLRTypeToDbType(c)};
xml.AppendLine(string.Format("<result property=\"{0}\" column=\"{1}\" type=\"{2}\" dbType=\"{3}\"/>", args1));
}
xml.AppendLine("</resultMap>");
return xml.ToString();
}
private void IBatisStatements( IColumns Columns )
{
%>
<insert id="Insert" parameterClass="<%= _className %>">
INSERT INTO <%= _tableName %> (<%= CombColumn(AddDelegate1, ", ") %>)
VALUES (<%= CombColumn(delegate(StringBuilder sb, string columnName, string propName) { sb.Append(string.Format("#{0}#", propName)); }, ", ") %>)
<selectKey resultClass="int" type="post" property="Id">
SELECT IDENT_CURRENT('<%= _tableName %>')
</selectKey>
</insert>
<update id="Update" parameterClass="<%= _className %>">
UPDATE <%= _tableName %> SET <%= CombColumn(delegate(StringBuilder sb, string columnName, string propName) { sb.Append(string.Format("{0} = #{1}#", columnName, propName)); }, ", ") %>
WHERE <%= GetColumnName("Id") %> = #Id# AND <%= GetColumnName("DeleteTime") %> IS NULL
</update>
<update id="DeleteById" parameterClass="int">
UPDATE <%= _tableName%> SET <%= GetColumnName("DeleteTime") %> = GETDATE()
WHERE <%= GetColumnName("Id") %> = #Id# AND <%= GetColumnName("DeleteTime") %> IS NULL
</update>
<sql id="SelectFrom">
FROM <%= _tableName%>
</sql>
<sql id="SqlWhereBase">
WHERE <%= GetColumnName("DeleteTime") %> IS NULL
<isNotNull prepend="AND" property="Id">
<%= GetColumnName("Id") %> = #Id#
</isNotNull>
<isNotNull prepend="" property="Ids">
<iterate prepend="AND" open="(" close=")" conjunction="OR" property="Ids">
<%= GetColumnName("Id") %> = #Ids[]#
</iterate>
</isNotNull>
<!---->
</sql>
<sql id="SelectCond">
<include refid="SqlWhereBase" />
<include refid="SqlWhereCustom" />
</sql>
<sql id="SelectOrder">
ORDER BY <%= GetColumnName("Id") %> ASC
</sql>
<select id="SelectCount" parameterClass="hashtable" resultClass="int">
SELECT COUNT(*)
<include refid="SelectFrom" />
<include refid="SelectCond" />
</select>
<select id="Select" parameterClass="hashtable" resultMap="<%= _className %>Result">
SELECT *
<include refid="SelectFrom"/>
<include refid="SelectCond"/>
<include refid="SelectOrder"/>
</select>
<select id="SelectByPage" parameterClass="hashtable" resultMap="<%= _className %>Result">
SELECT TOP $PageSize$ *
<include refid="SelectFrom" />
<include refid="SelectCond" />
AND <%= GetColumnName("Id") %> NOT IN
(SELECT TOP $NotInSize$ <%= GetColumnName("Id") %>
<include refid="SelectFrom" />
<include refid="SelectCond" />
<include refid="SelectOrder" />
)
<include refid="SelectOrder" />
</select>
<sql id="SqlWhereCustom">
</sql>
<%
}
#region ---------版本信息---------
private void Version()
{
output.writeln("///\t作 者:相润通");
output.writeln("///\t版本:1.0");
output.writeln("///\t时间: " + DateTime.Now);
}
#endregion
#region ---------工具方法---------
// 这个表是否被选中
private bool IsSelect(string _strTableName)
{
foreach (string _strTableName2 in _selectedTables)
{
if (_strTableName2.Equals(_strTableName))
{
return true;
}
}
return false;
}
// 去掉表前缀,得到的类名
private string TableToClassName(ITable table)
{
string tableName = table.Alias;
tableName= tableName.Replace(" ", "");
string name = RemoveFirstUnderlinePrefix(tableName);
return name.Substring(0, 1).ToUpper() + name.Substring(1, name.Length - 1);
}
//第一个字母大写
private string FirstToUpper(string columnName)
{
string name = RemoveFirstUnderlinePrefix(columnName);
return name.Substring(0, 1).ToUpper() + name.Substring(1, name.Length - 1);
}
//移除第一个下划线以前的字符
private string RemoveFirstUnderlinePrefix(string str)
{
int i = str.IndexOf('_');
if (i >= 0)
return str.Substring(i + 1, str.Length - i - 1);
else
return str;
}
//得到列前缀
public string GetColumnPrefix()
{
string str = _workingTable.Columns[0].Name;
int i = str.IndexOf('_');
if (i >= 0)
{
return str.Substring(0, i + 1);
}
else
{
return string.Empty;
}
}
//除去前缀的字符
public string RemoveColumnPrefix(string columnName)
{
string columnPrefix = GetColumnPrefix();
if (!string.IsNullOrEmpty(columnPrefix) && columnName.StartsWith(columnPrefix))
return columnName.Substring(columnPrefix.Length, columnName.Length - columnPrefix.Length);
return columnName;
}
public string GetColumnName(string propName)
{
return GetColumnPrefix() + propName;
}
public void SetBeanName()
{
_beanName=_className.Substring(0,1).ToLower()+_className.Substring(1,_className.Length-1);
}
protected string GetPK()
{
ITable Table = MyMeta.Databases[_dbName].Tables[_tableName];
string value = "";
foreach (IColumn Column in Table .Columns)
{
if (Column.IsInPrimaryKey)
{
value = Column.Alias;
}
}
return value;
}
#endregion
public string CombColumn(CombDelegate delegate1, string separator)
{
StringBuilder sb = new StringBuilder();
string columnPrefix = GetColumnPrefix();
//不是主键的每个字段
for (int i = 0; i < _workingTable.Columns.Count; i++)
{
//不是PrimaryKey
if (!_workingTable.Columns[i].IsInPrimaryKey)
{
string columnName = _workingTable.Columns[i].Name;
if(!columnName.Equals(GetColumnName("RecordTime"), StringComparison.OrdinalIgnoreCase) && !columnName.Equals(GetColumnName("DeleteTime"), StringComparison.OrdinalIgnoreCase))
{
if (!string.IsNullOrEmpty(separator) && sb.Length != 0)
{
sb.Append(separator);
}
delegate1(sb, columnName, RemoveColumnPrefix(columnName));
}
}
}
return sb.ToString();
}
/*
*
*sg :StringBuilder
*columnName:列名
*propName :除去前缀的列名
*column :列的ColumnSchema
*/
public delegate void CombDelegate(StringBuilder sg, string columnName, string propName);
//第一个委托
//Add
public void AddDelegate1(StringBuilder sb, string columnName, string propName)
{
sb.Append(columnName);
}
public void AddDelegate2(StringBuilder sb, string columnName, string propName)
{
sb.Append(string.Format("@{0}", propName));
}
//Update
public void UpdateDelegate1(StringBuilder sb, string columnName, string propName)
{
sb.Append(string.Format("{0} = @{1}", columnName, propName));
}
// Convert CLR type to SqlDbType
private string CLRTypeToDbType( IColumn Column )
{
string retVal = Column.LanguageType;
switch( Column.LanguageType )
{
case "Byte[]":
case "byte[]":
retVal = "Binary";
break;
case "Boolean":
retVal = "Bit";
break;
case "Byte":
retVal = "TinyInt";
break;
case "DateTime":
retVal = "DateTime";
break;
case "decimal":
retVal = "Real";
break;
case "numeric":
retVal = "Real";
break;
case "float":
retVal = "Real";
break;
case "double":
retVal = "Real";
break;
case "int":
retVal = "Int";
break;
case "Int16":
retVal = "SmallInt";
break;
case "Int32":
retVal = "Int";
break;
case "Int64":
retVal = "BigInt";
break;
case "string":
retVal = "varchar";
break;
case "single":
retVal = "Real";
break;
case "UInt16":
retVal = "Int";
break;
case "UInt32":
retVal = "Decimal";
break;
}
return retVal;
}
// Convert CLR type to IBatis type alias
private string CLRTypeToIBatisType( IColumn Column )
{
string retVal = Column.LanguageType;
switch( Column.LanguageType )
{
case "numeric":
retVal = "single";
break;
case "decimal":
retVal = "single";
break;
case "float":
retVal = "single";
break;
case "byte[]":
retVal = "Byte";
break;
}
return retVal;
}
}
%>