最近改进了下Nhibernate Object mapping template. 添加了class string type的长度。access level 为public const.
并且自动生成one -to -many的关系。 添加xml serializable attribute 在每个IList上。
下面为MyGeneration(下载地址) template code:
<%#NAMESPACE System.IO, System.Text, System.Text.RegularExpressions, System.Globalization %><%
public class GeneratedTemplate : DotNetScriptTemplate
{
private ArrayList _selectedTables;
private ArrayList _selectedViews;
private string _dbName;
private string _tableName;
private string _className;
private string _assemblyName;
private string _exportPath;
private string _fileName;
private string _nameSpace;
private string _prefix;
private string _using;
private bool _createClassFiles;
private bool _createXmlFiles;
private bool _createReadOnly;
private bool _generateEqualsHashCode;
private bool _generateDefaultCtor;
private bool _generateRequiredFieldsCtor;
private bool _includePKInReqFieldsCtorArgs;
public GeneratedTemplate( ZeusContext context ) : base( context ) {}
public override void Render()
{
_dbName = input["chooseDatabase"].ToString();
_selectedTables = input["chooseTables"] as ArrayList;
_selectedViews = input["chooseViews"] as ArrayList;
_exportPath = input["outputPath"].ToString();
_nameSpace = input["classNamespace"].ToString();
_assemblyName = input["assemblyName"].ToString();
_using = input["classUsing"].ToString();
_prefix = input["memberPrefix"].ToString();
_createClassFiles = (bool)input["chkClass"];
_createXmlFiles = (bool)input["chkMapping"];
_createReadOnly = (bool)input["chkReadOnly"];
_generateEqualsHashCode = (bool)input["chkEqualsHashCode"];
_generateDefaultCtor = (bool) input["chkDefaultEmptyConstructor"];
_generateRequiredFieldsCtor = (bool) input["chkRequiredFieldsConstructor"];
_includePKInReqFieldsCtorArgs = (bool) input["chkIncludePKInReqFieldsCtorArgs"];
foreach( string _newTable in _selectedTables )
{
ITable _workingTable = MyMeta.Databases[_dbName].Tables[_newTable];
_tableName = _workingTable.Alias.Replace( " ", "" );
_className = ToPascalCase( _tableName );
if( _createClassFiles )
{
GenerateClassFile( _workingTable.Columns );
}
if( _createXmlFiles )
{
GenerateMappingFile( _workingTable.Columns );
}
}
foreach( string _newView in _selectedViews )
{
IView _workingView = MyMeta.Databases[_dbName].Views[_newView];
_tableName = _workingView.Alias.Replace( " ", "" );
_className = ToPascalCase( _tableName );
if( _createClassFiles )
{
GenerateClassFile( _workingView.Columns );
}
if( _createXmlFiles )
{
GenerateMappingFile( _workingView.Columns );
}
}
}
private void GenerateClassFile( IColumns Columns )
{
output.writeln( "using System;" );
output.writeln( "using System.Collections;" );
output.writeln( "using System.Xml.Serialization;" );
output.writeln( _using);
output.writeln( "" );
output.write( "namespace " );
output.writeln( _nameSpace );
output.writeln( "{" );
output.writeln( "\t/// <summary>" );
output.writeln( "\t///\tGenerated by MyGeneration using the NHibernate Object Mapping template" );
output.writeln( "\t/// </summary>" );
output.writeln( "\t[Serializable]" );
output.write( "\tpublic class " );
output.writeln( _className );
output.writeln( "\t{" );
BuildPrivateMembers( Columns );
if( _generateDefaultCtor )
BuildDefaultConstructor( Columns );
if( _generateRequiredFieldsCtor )
BuildRequiredFieldsCtor( Columns );
BuildPublicAccessors( Columns );
//BuildInternalAccessors( Columns );
BuildPublicFunctions (Columns);
if( _generateEqualsHashCode )
BuildEqualsHashCodeOverrides( Columns );
output.writeln( "" );
output.writeln( "\t}" );
output.writeln( "}" );
_fileName = _className + ".cs";
output.save( Path.Combine( _exportPath, _fileName ), false );
output.clear();
}
private void GenerateMappingFile( IColumns Columns )
{
BuildHBMDefinition( Columns );
_fileName = _className + ".hbm.xml";
output.save( Path.Combine( _exportPath, _fileName ), false );
output.clear();
}
private void BuildDefaultConstructor( IColumns Columns )
{
%>
#region Constuctor
public <%= _className %>()
{<%
foreach( IColumn field in Columns )
{
string fieldName = ColumnToMemberVariable( field )/*.Replace( "_id", "")*/;
string fieldType = ( field.IsInForeignKey && !field.IsInPrimaryKey ? ColumnFKToClassName( field) : ColumnToNHibernateType( field ) );
if( fieldType.EndsWith( "[]" ) )
{%>
<%= fieldName %> = new <%= fieldType %>{}; <%
}
else
{
switch( fieldType )
{
case "string":%>
<%= fieldName %> = String.Empty; <%
break;
case "DateTime":%>
<%= fieldName %> = DateTime.MinValue; <%
break;
case "bool":%>
<%= fieldName %> = false; <%
break;
case "decimal":
case "float":
case "short":
case "int":
case "long":%>
<%= fieldName %> = 0; <%
break;
default:%>
<%= fieldName %> = new <%= fieldType %>(); <%
break;
}
}
if( field.IsInForeignKey && field.IsInPrimaryKey )
{
//Here, there are foreign key relationships to this column,
//so there are collections in this class that represent those relationships.
//Initialize them.
foreach( IForeignKey fk in field.ForeignKeys )
{
output.writeln("");
output.write("\t\t\t");
output.write( _prefix );
output.write( fk.ForeignTable.Alias.Replace( " ", "" ) );
output.write( " = new List<" + ToPascalCase( fk.ForeignTable.Alias.Replace( " ", "" ) ) + ">(); " );
}
}
}
output.writeln( "" );
output.writeln( "\t\t}" );
output.writeln( "" );
output.writeln( "\t\t#endregion // End of Default ( Empty ) Class Constuctor" );
}
private void BuildRequiredFieldsCtor( IColumns Columns )
{
//If there are no required fields, don't make a ctor.
//Doing so will give a compiler error, since the result will
//have the same signature as the default ctor.
if( CountRequiredFields( Columns ) == 0 )
return;
output.writeln( "" );
//output.writeln( "\t\t#region Required Fields Only Constructor" );
//output.writeln( "\t\t/// <summary>" );
//output.writeln( "\t\t/// required (not null) fields only constructor" );
//output.writeln( "\t\t/// </summary>" );
output.write( "\t\tpublic " );
output.write( _className );
output.writeln( "(" );
bool first = true;
foreach( IColumn col in Columns )
{
if( !col.IsNullable && ( !col.IsInPrimaryKey || _includePKInReqFieldsCtorArgs ) )
{
if( !first )
{
output.writeln( ", " );
}
output.write( "\t\t\t" );
if( col.IsInForeignKey && !col.IsInPrimaryKey )
output.write( ColumnFKToClassName( col ).Replace( "_id", "") );
else
output.write( ColumnToNHibernateType( col ).Replace( "_id", "") );
output.write( " " + ColumnToArgumentName( col ).Replace( "_id", "") );
first = false;
}
}
output.writeln( ")" );
output.writeln( "\t\t\t: this()" );
output.writeln( "\t\t{" );
foreach( IColumn col in Columns )
{
if( col.IsInPrimaryKey && !_includePKInReqFieldsCtorArgs )
{
//Skip the primary key field, if instructed to do so.
continue;
}
output.write( "\t\t\t" );
if( !col.IsNullable && ( !col.IsInPrimaryKey || _includePKInReqFieldsCtorArgs ) )
{
output.write( "this." + ColumnToMemberVariable( col )/*.Replace( "_id", "") */);
output.write( " = " );
output.write( ColumnToArgumentName( col )/*.Replace( "_id", "")*/ );
output.writeln( ";" );
}
else
{
string fieldType = ( col.IsInForeignKey && !col.IsInPrimaryKey
? ColumnFKToClassName( col )
: ColumnToNHibernateType( col ) );
switch( fieldType )
{
default:
output.write( "this." + ColumnToMemberVariable( col )/*.Replace( "_id", "")*/ );
output.writeln( " = null;" );
break;
case "string":
output.write( "this." + ColumnToMemberVariable( col )/*.Replace( "_id", "")*/ );
output.writeln( " = String.Empty;" );
break;
case "DateTime":
output.write( "this." + ColumnToMemberVariable( col )/*.Replace( "_id", "")*/);
output.writeln( " = DateTime.MinValue;" );
break;
case "bool":
output.write( "this." + ColumnToMemberVariable( col )/*.Replace( "_id", "")*/ );
output.writeln( " = false;" );
break;
case "decimal":
case "float":
case "short":
case "int":
case "long":
output.write( "this." + ColumnToMemberVariable( col )/*.Replace( "_id", "")*/ );
output.writeln( " = 0;" );
break;
}
}
}
output.writeln( "\t\t}" );
output.writeln( "\t\t//#endregion // End Constructor" );
}
private void BuildFullConstructor( IColumns Columns )
{
%>#region Full Constructor
/// <summary>
/// full constructor
/// </summary>
public <%= _className %>(<%
bool first = true;
foreach( IColumn field in Columns )
{
if( !first ) output.write( ", " );
output.write( ( field.IsInForeignKey && !field.IsInPrimaryKey ? ToPascalCase( field.ForeignKeys[0].PrimaryTable.Alias.Replace( " ", "" ) ) : ColumnToNHibernateType( field ) ) + " " + ColumnToArgumentName( field ) );
first = false;
}%>)
{<%
foreach( IColumn col in Columns )
{
%>
<%= ColumnToMemberVariable( col )/*.Replace( "_id", "")*/ %> = <%= ColumnToArgumentName( col )/*.Replace( "_id", "")*/ %>; <%
}
%>
}
#endregion // End Full Constructor<%
}
private void BuildEqualsHashCodeOverrides( IColumns Columns )
{
%>
#region Equals And HashCode Overrides
/// <summary>
/// local implementation of Equals based on unique value members
/// </summary>
public override bool Equals( object obj )
{
if( this == obj ) return true;
if( ( obj == null ) || ( obj.GetType() != this.GetType() ) ) return false;
<%= _className %> castObj = (<%= _className %>)obj; <%
if( CountUniqueFields( Columns ) == 0 )
{%>
return castObj.GetHashCode() == this.GetHashCode()<%
}
else
{%>
return ( castObj != null )<%
foreach( IColumn c in Columns )
{
if( c.IsInPrimaryKey )
{
%> &&
( this.<%= ColumnToMemberVariable( c ) %> == castObj.<%= ColumnToPropertyName( c ) %> )<%
}
}
} %>;
}
/// <summary>
/// local implementation of GetHashCode based on unique value members
/// </summary>
public override int GetHashCode()
{
<% if( CountUniqueFields( Columns ) == 0 )
{
%>return this.GetType().FullName.GetHashCode();
<%
}
else
{%>
int hash = 57; <%
foreach( IColumn c in Columns )
{
if( c.IsInPrimaryKey )
{
%>
hash = 27 * hash * <%= ColumnToMemberVariable( c ) %>.GetHashCode();<%
}
}
%>
return hash; <%
}%>
}
#endregion
<%
}
private void BuildPrivateMembers( IColumns Columns )
{
if( Columns.Count > 0 )
{
%>
#region Private Members
<%
foreach( IColumn field in Columns )
{
if( field.IsInForeignKey )
{
if ( !field.IsInPrimaryKey )
{
// A column that's in a fk but not in the pk is an actual foreign key,
// a many-to-one relationship. So the member variable is a class instance.
%>
private <%= ToPascalCase( field.ForeignKeys[0].PrimaryTable.Alias.Replace( " ", "" ) ) %> <%= ColumnToMemberVariable( field )/*.Replace( "_id", "")*/ %>; <%
}
else
{
//A column that's in a fk and in the pk represents a fk relationship
//from another table, a one-to-many relationship. (This might be
//a bad assumption for a table with a composite primary key.)
//So we have to add the pk member variable itself...
%>
private <%= ColumnToNHibernateType( field ) %> <%= ColumnToMemberVariable( field )/*.Replace( "_id", "")*/ %>; <%
//... and then we have to add collections for the foreign tables.
foreach( IForeignKey fk in field.ForeignKeys )
{
output.writeln("");
output.write( "\t\tprivate IList " );
output.write( _prefix );
output.write( fk.ForeignTable.Alias.Replace( " ", "" ) );
output.write( ";" );
}
}
}
else
{%>
private <%= ColumnToNHibernateType( field ) %> <%= ColumnToMemberVariable( field )/*.Replace( "_id", "")*/ %>; <%
}
}
%>
#endregion
<%
}
}
private void BuildInternalAccessors( IColumns Columns )
{
if( Columns.Count > 0 )
{
%>
#region Private Accessors for NHibernate
<%
foreach( IColumn field in Columns )
{
string fieldAccessor = ColumnToNHibernateProperty( field );
string fieldName = ColumnToMemberVariable( field );
string fieldType = ( field.IsInForeignKey && !field.IsInPrimaryKey ? ToPascalCase( field.ForeignKeys[0].PrimaryTable.Alias.Replace( " ", "" ) ) : ColumnToNHibernateType( field ) );
%>
private <%= fieldType %> _<%= fieldAccessor %>
{
get { return <%= fieldName %>; }
set { <%= fieldName %> = value; }
}
<%
}
%>
#endregion // Internal Accessors for NHibernate
<%
}
}
private void BuildPublicAccessors( IColumns Columns )
{
if( Columns.Count > 0 )
{
%>
#region Public Properties
<%
foreach( IColumn field in Columns )
{
string fieldAccessor = ColumnToPropertyName( field )/*.Replace( "Id", "")*/;
string fieldName = ColumnToMemberVariable( field )/*.Replace( "_id", "")*/;
string fieldType = ( field.IsInForeignKey && !field.IsInPrimaryKey ? ToPascalCase( field.ForeignKeys[0].PrimaryTable.Alias.Replace( " ", "" ) ) : ColumnToNHibernateType( field ) );
output.writeln( "" );
if(field.CharacterMaxLength > 0)
{
output.writeln( "\t\t public const int " + fieldAccessor + "MaxLength = " + field.CharacterMaxLength +";" );
}
output.writeln( "\t\tpublic virtual " + fieldType + " " + fieldAccessor );
output.writeln( "\t\t{" );
output.writeln( "\t\t\tget { return " + fieldName + "; }" );
if( !_createReadOnly )
{
switch( fieldType )
{
default:
output.writeln( "\t\t\tset" );
output.writeln( "\t\t\t{" );
if( !field.IsNullable && !IsValueType( fieldType ) )
{
output.writeln( "\t\t\t\tif( value == null )" );
output.writeln( "\t\t\t\t\tthrow new ArgumentOutOfRangeException(\"Null value not allowed for " + fieldAccessor + "\", value, \"null\");" );
output.writeln( "" );
}
output.write( "\t\t\t\t" );
output.write( fieldName );
output.writeln( " = value;" );
output.writeln( "\t\t\t}" );
break;
case "byte": %>
set
{ <%if( !field.IsNullable )
{%>
if( value == null )
throw new ArgumentOutOfRangeException("Null value not allowed for <%= fieldAccessor %>", value, "null");
<%}%>
if( <%if( field.IsNullable ) {%> value != null && <%}%> value.Length > <%= field.CharacterMaxLength.ToString() %>)
throw new ArgumentOutOfRangeException("Invalid value for <%= fieldAccessor %>", value, value.ToString());
<%= fieldName %> = value;
}
<%
break;
case "string": %>
set
{ <%if( !field.IsNullable )
{%>
if( value == null )
throw new ArgumentOutOfRangeException("Null value not allowed for <%= fieldAccessor %>", value, "null");
<%}%>
if( <%if( field.IsNullable ) {%> value != null && <%}%> value.Length > <%= field.CharacterMaxLength.ToString() %>)
throw new ArgumentOutOfRangeException("Invalid value for <%= fieldAccessor %>", value, value.ToString());
<%= fieldName %> = value;
}<%
break;
}
//}
}%>
}
<%
if( field.IsInForeignKey && field.IsInPrimaryKey )
{
//This means that there are collections implementing
//one-to-many relationships based on this column. So
//we need accessors for those collections, too.
foreach( IForeignKey fk in field.ForeignKeys )
{
output.writeln( "" );
output.writeln( "\t\t[System.Xml.Serialization.XmlArrayItem(typeof("+ToPascalCase( fk.ForeignTable.Alias.Replace( " ", "" ) )+"))]" );
output.writeln( "\tpublic virtual IList " + ToPascalCase( fk.ForeignTable.Alias.Replace( " ", "" ) ) + "s" );
output.writeln( "\t\t{" );
output.writeln( "\t\t\tget" );
output.writeln( "\t\t\t{" );
output.writeln( "\t\t\t\treturn " + _prefix + fk.ForeignTable.Alias.Replace( " ", "" ) + ";" );
output.writeln( "\t\t\t}" );
output.writeln( "\t\t\tset" );
output.writeln( "\t\t\t{" );
output.writeln( "\t\t\t\t" + _prefix + fk.ForeignTable.Alias.Replace( " ", "" ) + " = value;" );
output.writeln( "\t\t\t}" );
output.writeln( "\t\t}" );
}
}
}
%>
#endregion
<%
}
}
private void BuildPublicFunctions( IColumns Columns )
{
if( Columns.Count > 0 )
{
%>
#region Public Functions
#endregion //Public Functions
<%
}
}
private void BuildHBMDefinition( IColumns Columns )
{
if( Columns.Count > 0 )
{
output.writeln( "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" );
output.writeln( NHibernateMappingTag() );
output.writeln( "\t" + NHibernateClassTag( Columns ) );
output.writeln( "\t\t" + NHibernatePrimaryKeysTag( Columns ) );
output.writeln( "\t\t" + NHibernateProperties( Columns ) );
output.writeln( "\t</class>" );
output.writeln( "</hibernate-mapping>" );
}
}
private string NHibernateMappingTag()
{
//// can't handle external mappings ?!?
////string xml = "<hibernate-mapping xmlns=\"http://nhibernate.sourceforge.net/schemas/nhibernate-mapping-2.0.xsd\"";
//string xml = "<hibernate-mapping xmlns=\"urn:nhibernate-mapping-2.0\"";
//// handle schemas, cascade, import, and access methods?
//return xml + ">";
return "<hibernate-mapping xmlns=\"urn:nhibernate-mapping-2.0\" assembly=\"" + _nameSpace + "\" namespace=\"" + _nameSpace + "\">";
}
private string NHibernateClassTag( IColumns Columns )
{
//ITable t = Columns[0].Table;
//IView v = Columns[0].View;
//string desc = ( t == null ) ? v.Description : t.Description;
StringBuilder xml = new StringBuilder();
xml.Append( "<class name=\"" ).Append( _className ).Append( "\"" );
xml.Append( " table=\"" ).Append( _tableName ).Append( "\"" ).Append( " lazy=\"false\" " );
if( _createReadOnly )
{
xml.Append( " mutable=\"false\"" );
}
// handle schema override, dynamic insert & update, and proxies?
xml.Append( ">\r\n" );
return xml.ToString();
}
private string NHibernatePrimaryKeysTag( IColumns Columns )
{
StringBuilder xml = new StringBuilder();
int i = 0;
foreach( IColumn c in Columns )
{
if( c.IsInPrimaryKey )
{
i++;
}
}
if( i == 0 )
{
return "<!-- could not find a primary key for this table/view. NHibernate requires an 'id' element, so you'll have to define one manually. -->";
}
if( i == 1 )
{
foreach( IColumn c in Columns )
{
if( c.IsInPrimaryKey )
{
xml.Append( "<id name=\"" ).Append( ColumnToPropertyName( c ) ).Append( "\" column=\"" );
xml.Append( c.Alias ).Append( "\" type=\"" ).Append( ConvertNHibernate( ColumnToNHibernateType( c ) ) ).Append( "\"" );
switch( ColumnToNHibernateType( c ) )
{
case "decimal":
case "float":
case "short":
case "int":
case "long":
xml.Append( " unsaved-value=\"0\">\r\n" );
break;
default:
xml.Append( ">\r\n" );
break;
}
xml.Append( "\t\t\t<generator class=\"" );
xml.Append( ( c.IsAutoKey ) ? "native" : "assigned" );
xml.Append( "\"/>\r\n\t\t</id>" );
}
}
}
if( i > 1 )
{
xml.Append( "<!-- composite primary key support is touchy. View the documentation for syntax. -->" );
}
return xml.ToString();
}
private string NHibernateProperties( IColumns Columns )
{
StringBuilder xml = new StringBuilder();
foreach( IColumn c in Columns )
{
if( !c.IsInPrimaryKey )
{
// create sets & such for foreign keys !!!
if( c.IsInForeignKey )
{
if( c.ForeignKeys.Count > 1 )
{
xml.Append( "<!-- more than one foreign column is mapped to " ).Append( c.Name ).Append( " - you're on your own. -->\r\n\t\t" );
}
else
{
IForeignKey fk = c.ForeignKeys[0];
xml.Append( "<many-to-one name=\"" )
.Append( ColumnToPropertyName( c ) )
.Append( "\" column=\"" )
.Append( c.Name );
xml.Append( "\" class=\"" )
.Append( _nameSpace+".")
.Append( ToPascalCase( fk.PrimaryTable.Alias.Replace( " ", "" ) ) )
.Append( ","+_assemblyName)
.Append( "\" />\r\n\t\t" );
}
}
else
{
xml.Append( "<property column=\"" ).Append( c.Name );
xml.Append( "\" type=\"" ).Append( ConvertNHibernate( ColumnToNHibernateType( c ) ) ).Append( "\"" );
if( _createReadOnly )
{
xml.Append( " access=\"field\" name=\"" ).Append( ColumnToMemberVariable( c ) ).Append( "\"" );
}
else
{
xml.Append( " name=\"" ).Append( ColumnToPropertyName( c ) ).Append( "\"" );
//xml.Append( " name=\"" ).Append( ColumnToNHibernateProperty( c ) ).Append( "\"" );
}
if( !c.IsNullable )
{
xml.Append( " not-null=\"true\"" );
}
//if( c.LanguageType == "string" )
//{
// xml.Append( " length=\"" ).Append( c.CharacterMaxLength ).Append( "\"" );
//}
xml.Append( " />\r\n\t\t" );
}
}
else
{ // c.IsInPrimaryKey is true here
if( c.IsInForeignKey )
{
//Here's where we handle one-to-many relations. A column that is in the PK, and is involved in FK relatioships,
//means it's the one in the one-to-many.
foreach( IForeignKey fk in c.ForeignKeys )
{
//Use a bag, since we don't know the real relationship.
xml.Append( "<bag ");
//The name for the collection property in the class.
//Made from the class name of the "many" side of the
//relationship, with "List" appended.
xml.Append( "name=\"" )
.Append( ToPascalCase( fk.ForeignTable.Alias.Replace( " ", "" ) ) )
.Append( "s\" " );
//This means that persisting the class object that contains this
//collection will not cause the collection's elements to be persisted.
//You have to navigate the collection and persist them individually.
xml.Append( "inverse=\"true\" " );
//Lazy loading. The collection is not filled until the application needs it.
xml.Append( "lazy=\"false\" " );
//generics update for bag relations.
//xml.Append( "generic=\"true\" ")
xml.Append( ">\r\n" );
//The key element specifies the column in the owning class/table that is the
//foreign key for the collection's class/table. Note this code only supports
//single-column foreign keys.
if( fk.ForeignColumns.Count > 1 )
{
xml.Append( "<!-- Composite foreign keys are not supported in this template. -->\r\n" );
}
else
{
xml.Append( "\t\t\t<key column=\"" )
.Append( fk.ForeignColumns[0].Name )
.Append( "\" />\r\n" );
}
//the one-to-many tag specifies the class of the objects in the
//collection, the "many" side.
xml.Append( "\t\t\t<one-to-many class=\"" )
.Append( _nameSpace+".")
.Append( ToPascalCase( fk.ForeignTable.Alias.Replace( " ", "" ) ) )
.Append( ","+_assemblyName)
.Append( "\" />\r\n" );
//Close the bag tag and indent for the next column.
xml.Append( "\t\t</bag>\r\n\t\t" );
}
}
}
}
return xml.ToString();
}
private string ConvertNHibernate( string Type )
{
string retVal = Type;
switch( Type )
{
case "bool":
retVal = "Boolean";
break;
case "byte":
retVal = "Byte";
break;
case "sbyte":
retVal = "SByte";
break;
case "char":
retVal = "Char";
break;
case "decimal":
retVal = "Decimal";
break;
case "double":
retVal = "Double";
break;
case "float":
retVal = "Single";
break;
case "int":
retVal = "Int32";
break;
case "uint":
retVal = "UInt32";
break;
case "long":
retVal = "Int64";
break;
case "ulong":
retVal = "UInt64";
break;
case "short":
retVal = "Int16";
break;
case "ushort":
retVal = "UInt16";
break;
case "string":
retVal = "String";
break;
}
return retVal;
}
private string ColumnToMemberVariable( IColumn Column )
{
return _prefix + UniqueColumn( Column ).ToLower();
}
private string ColumnToPropertyName( IColumn Column )
{
return ToPascalCase( UniqueColumn( Column ) );
}
private string ColumnFKToClassName( IColumn c )
{
return ToPascalCase( c.ForeignKeys[0].PrimaryTable.Alias.Replace( " ", "" ) );
}
private string ColumnToArgumentName( IColumn Column )
{
return UniqueColumn( Column ).ToLower();
}
private string ColumnToNHibernateProperty( IColumn Column )
{
return _prefix + UniqueColumn( Column );
}
private string UniqueColumn( IColumn Column )
{
string c = Column.Alias.Replace( " ", "" );
if( Column.Table != null && Column.Table.Alias.Replace( " ", "" ) == c )
{
c += "Name";
}
if( Column.View != null && Column.View.Alias.Replace( " ", "" ) == c )
{
c += "Name";
}
return c;
}
// nhibernate doesn't have these, so use the existing types
private string ColumnToNHibernateType( IColumn Column )
{
string retVal = Column.LanguageType;
switch( Column.LanguageType )
{
case "sbyte":
retVal = "byte";
break;
case "uint":
retVal = "int";
break;
case "ulong":
retVal = "long";
break;
case "ushort":
retVal = "short";
break;
}
return retVal;
}
private bool IsValueType( string type )
{
switch( type )
{
case "sbyte":
case "byte":
case "short":
case "ushort":
case "int":
case "uint":
case "long":
case "ulong":
case "char":
case "float":
case "double":
case "bool":
case "decimal":
case "DateTime":
return true;
break;
default:
return false;
break;
}
}
private string ToLeadingCaps( string name )
{
char[] chars = name.ToLower().ToCharArray();
chars[0] = Char.ToUpper( chars[0] );
return new string( chars );
}
private string ToLeadingLower( string name )
{
char[] chars = name.ToCharArray();
chars[0] = Char.ToLower( chars[0] );
return new string( chars );
}
private string ToPascalCase( string name )
{
string notStartingAlpha = Regex.Replace( name, "^[^a-zA-Z]+", "" );
string workingString = ToLowerExceptCamelCase( notStartingAlpha );
workingString = RemoveSeparatorAndCapNext( workingString );
return workingString;
}
private string RemoveSeparatorAndCapNext( string input )
{
//string dashUnderscore = "-_";
string dashUnderscore = "-";
string workingString = input;
char[] chars = workingString.ToCharArray();
int under = workingString.IndexOfAny( dashUnderscore.ToCharArray() );
while( under > -1 )
{
chars[ under + 1 ] = Char.ToUpper( chars[ under + 1 ], CultureInfo.InvariantCulture );
workingString = new String( chars );
under = workingString.IndexOfAny( dashUnderscore.ToCharArray(), under + 1 );
}
chars[ 0 ] = Char.ToUpper( chars[ 0 ], CultureInfo.InvariantCulture );
workingString = new string( chars );
return Regex.Replace( workingString, "[-]", "" );//Regex.Replace( workingString, "[-_]", "" );
}
private string ToLowerExceptCamelCase( string input )
{
char[] chars = input.ToCharArray();
for( int i = 0; i < chars.Length; i++ )
{
int left = ( i > 0 ? i - 1 : i );
int right = ( i < chars.Length - 1 ? i + 1 : i );
if( i != left && i != right )
{
if( Char.IsUpper( chars[i] ) && Char.IsLetter( chars[ left ] ) && Char.IsUpper( chars[ left ] ) )
{
chars[i] = Char.ToLower( chars[i], CultureInfo.InvariantCulture );
}
else if( Char.IsUpper( chars[i] ) && Char.IsLetter( chars[ right ] ) && Char.IsUpper( chars[ right ] ) )
{
chars[i] = Char.ToLower( chars[i], CultureInfo.InvariantCulture );
}
else if( Char.IsUpper( chars[i] ) && !Char.IsLetter( chars[ right ] ) )
{
chars[i] = Char.ToLower( chars[i], CultureInfo.InvariantCulture );
}
}
}
chars[ chars.Length - 1 ] = Char.ToLower( chars[ chars.Length - 1 ], CultureInfo.InvariantCulture );
return new string( chars );
}
private int CountRequiredFields( IColumns Columns )
{
return Columns.Count - CountNullableFields( Columns );
}
private int CountNullableFields( IColumns Columns )
{
int i = 0;
foreach( IColumn c in Columns )
{
if( c.IsNullable )
{
i++;
}
}
return i;
}
private int CountUniqueFields( IColumns Columns )
{
int i = 0;
foreach( IColumn c in Columns )
{
if( !c.IsNullable && c.IsInPrimaryKey )
{
i++;
}
}
return i;
}
}
%>
下面为interface Code
<%#REFERENCE System.Windows.Forms.dll %>
<%#NAMESPACE System, System.Text, System.Collections, Zeus, Zeus.UserInterface, Zeus.DotNetScript %>
public class GeneratedGui : DotNetScriptGui
{
public GeneratedGui( ZeusGuiContext context ) : base( context ) {}
public override void Setup()
{
if ( !input.Contains( "chooseTables" ) || !input.Contains( "txtPath" ) ||
( !input.Contains( "chkClass" ) && !input.Contains( "chkNaming" ) ) )
{
ui.Title = "NHibernate Object Mapping";
ui.Width = 620;
ui.Height = 690;
// Grab default output path
string sOutputPath = "";
if( input.Contains( "defaultOutputPath" ) )
{
sOutputPath = input["defaultOutputPath"].ToString();
}
// Setup Folder selection input control.
GuiLabel label1 = ui.AddLabel( "label1", "Select the output path:", "Select the output path in the field below." );
label1.Width = 200;
GuiTextBox outputPath = ui.AddTextBox( "outputPath", sOutputPath, "Select the Output Path." );
outputPath.Width = 450;
GuiFilePicker selectPath = ui.AddFilePicker( "selectPath", "Select Path", "Select the Output Path.", "outputPath", true );
selectPath.Top = outputPath.Top;
selectPath.Width = 100;
selectPath.Left = outputPath.Left + outputPath.Width + 20;
GuiLabel label2 = ui.AddLabel( "label2", "Namespace: ", "Provide your objects namespace." );
label2.Width = 280;
GuiTextBox classNamespace = ui.AddTextBox( "classNamespace", "Entities", "Provide your objects namespace." );
classNamespace.Width = 280;
GuiLabel labeln = ui.AddLabel( "labeln", "assemblyName: ", "Provide your assembly Name ." );
labeln.Width = 280;
GuiTextBox assemblyName = ui.AddTextBox( "assemblyName", "Entities", "Provide your objects assembly name." );
classNamespace.Width = 280;
GuiLabel label3 = ui.AddLabel( "label3", "Member variable prefix: ", "Provide your Prefix." );
label3.Width = 280;
label3.Top = label2.Top;
label3.Left = label2.Width + 20;
GuiTextBox memberPrefix = ui.AddTextBox( "memberPrefix", "m_", "" );
memberPrefix.Width = 280;
memberPrefix.Top = classNamespace.Top;
memberPrefix.Left = classNamespace.Width + 20;
//Using
GuiLabel lblUsing = ui.AddLabel( "lblUsing", "Using: ", "Provide your custom using ...;" );
lblUsing.Width = 280;
GuiTextBox classUsing = ui.AddTextBox( "classUsing", "", "Provide your custom using ..." );
classUsing.Width = 280;
// Setup Database selection combobox.
GuiLabel label4 = ui.AddLabel( "label4", "Select a database:", "Select a database in the dropdown below." );
label4.Width = 250;
GuiComboBox chooseDatabase = ui.AddComboBox( "chooseDatabase", "Select a database." );
chooseDatabase.Width = 250;
GuiLabel label5 = ui.AddLabel( "label5", "Output type:", "Select one or both." );
label5.Width = 150;
label5.Top = label4.Top;
label5.Left = label4.Width + 20;
GuiCheckBox chkClass = ui.AddCheckBox( "chkClass", "Create class files.", true, "Create a class file for each table or view selected. (*.cs)" );
chkClass.Width = 150;
chkClass.Top = chooseDatabase.Top;
chkClass.Left = chooseDatabase.Width + 20;
GuiCheckBox chkMapping = ui.AddCheckBox( "chkMapping", "Create XML mapping files.", true, "Create an XML file for each table or view selected. (*.hbm.xml)" );
chkMapping.Width = 150;
chkMapping.Top = chkClass.Top + 20;
chkMapping.Left = chkClass.Left;
GuiLabel label6 = ui.AddLabel( "label6", "Read Only:", "Create as read only?" );
label6.Width = 150;
label6.Top = label5.Top;
label6.Left = label5.Left + label5.Width + 20;
GuiCheckBox chkReadOnly = ui.AddCheckBox( "chkReadOnly", "Create as read-only.", false, "Create object and mapping to have read-only access." );
chkReadOnly.Width = 150;
chkReadOnly.Top = chkClass.Top;
chkReadOnly.Left = chkClass.Left + chkClass.Width + 20;
GuiCheckBox chkDefaultEmptyConstructor = ui.AddCheckBox( "chkDefaultEmptyConstructor", "Create a default (empty) constructor. Required.", true, "Create a default constructor with empty fields." );
chkDefaultEmptyConstructor.Top = chkMapping.Top + 20;
GuiCheckBox chkRequiredFieldsConstructor = ui.AddCheckBox( "chkRequiredFieldsConstructor", "Create a constructor with all required (non-null) fields as parameters.", true, "Create a constructor with all required (non-null) fields as parameters" );
chkRequiredFieldsConstructor.Top = chkDefaultEmptyConstructor.Top + 20;
GuiCheckBox chkIncludePKInReqFieldsCtorArgs = ui.AddCheckBox( "chkIncludePKInReqFieldsCtorArgs", "Include primary key in required fields constructor.", true, "Include primary key in the parameter list for the required fields constructor." );
chkIncludePKInReqFieldsCtorArgs.Top = chkRequiredFieldsConstructor.Top + 20;
GuiCheckBox chkEqualsHashCode = ui.AddCheckBox