Nhiberante Template code 模板文件 -用于Mygeneration

<%#REFERENCE DDLLY.MyGenerationTemplate.dll %><%#NAMESPACE System.IO, System.Text, System.Text.RegularExpressions, System.Globalization,DDLLY.MyGenerationTemplate %><%
public class GeneratedTemplate : DDLNHibernateDotNetScriptTemplate
{
    //选中的表
    private IList _selectedTables;
    //选中的视图
    private IList _selectedViews;
    //数据库名
    private string _dbName;
    //表名
    private string _tableName;
    //类名
    private string _className;
    //输出路径
    private string _exportPath;
    //文件名
    private string _fileName;
    //命名空间
    private string _nameSpace;
    //创建类文件
    private bool _createClassFiles;
    //创建XML文件
    private bool _createXmlFiles;
    //只读访问
    private bool _createReadOnly;
    //创建Equals和HashCode
    private bool _generateEqualsHashCode;
    //在构造函数中使用Null
    private bool _useNull;
    //不创建外健引用
    //private bool _dontCreateFK;
    //使用Lazy类
    private bool _enableLazyClass;
    //启用nullable类型
    private bool _enableNullTypes;
    //程序集名称
    private string _assembly;
    
    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();
        _prefix = input["memberPrefix"].ToString();
        _createClassFiles = (bool)input["chkClass"];
        _createXmlFiles = (bool)input["chkMapping"];
        _createReadOnly = (bool)input["chkReadOnly"];
        _generateEqualsHashCode = (bool)input["chkEqualsHashCode"];
        _useNull = (bool)input["chkUseNull"];
        //_dontCreateFK = (bool)input["chkDontCreateFK"];
        _enableLazyClass = (bool)input["chkLazyClass"];
        _enableNullTypes = (bool)input["chkEnableNullTypes"];
        _assembly=input["txtAssembly"].ToString();
        
        _NullSufix = (_enableNullTypes ? "?" : "");
        
        

        foreach( string _newTable in _selectedTables )
        {
            ITable _workingTable = MyMeta.Databases[_dbName].Tables[_newTable];
            _tableName = _workingTable.Alias;
            _className = TableNameToClassName(_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 = TableNameToClassName(_tableName);
            if( _createClassFiles )
            {
                GenerateClassFile( _workingView.Columns );
            }
            if( _createXmlFiles )
            {
                GenerateMappingFile( _workingView.Columns );
            }
        }
    }
    
    private void GenerateClassFile( IColumns Columns )
    {
        _CreatingXML =false;
    
    %>/*
/*NHibernate映射代码模板
/*作者:DDL
/*版本更新和支持:http://renrenqq.cnblogs.com/
/*日期:2006年8月24日 
*/
using System;

namespace <%= _nameSpace %>
{
    /// <summary>
    ///    
    /// </summary>
    [Serializable]
    public <%=(_enableLazyClass ? "" : "sealed ")%>class <%= _className %>
    {
        <% BuildPrivateMembers( Columns ); %>
        
        <% BuildDefaultConstructor( Columns ); %>
        
        <% BuildPublicAccessors( Columns ); %>
        
        <% BuildPublicFunctions( Columns ); %>
        
        <% if( _generateEqualsHashCode ) BuildEqualsHashCodeOverrides( Columns ); %>
    }
}
<%
        _fileName = _className + ".cs";
        output.saveEnc( Path.Combine( _exportPath, _fileName ), false ,Encoding.GetEncoding("utf-8") );
        output.clear();
    }
    
    private void GenerateMappingFile( IColumns Columns )
    {
        _CreatingXML =true;
        
        BuildHBMDefinition( Columns );
        
        _fileName = _className + ".hbm.xml";
        output.saveEnc( Path.Combine( _exportPath, _fileName ), false ,Encoding.GetEncoding("utf-8") );
        output.clear();
    }
    
    private void BuildDefaultConstructor( IColumns Columns )
    {
        %>#region 默认( 空 ) 构造函数
        /// <summary>
        /// 默认构造函数
        /// </summary>
        public <%= _className %>()
        {<%
        foreach( IColumn field in Columns )
        {
            string fieldName = ToVariableName(field.Alias);
            string fieldType = ColumnToNHibernateType(field );
            
            if( fieldType.EndsWith( "[]" ) )
            {%> 
            <%= fieldName %> = new <%= fieldType %>{}; <%
            }
            else
            {
                switch( fieldType )
                {
                    case "string":%>
            <%= fieldName %> = <% 
                        if(_useNull){ %>null; <% }
                        else {%> String.Empty; <%     }
                        break;
                    case "DateTime":%>
            <%= fieldName %> = DateTime.MinValue; <%
                        break;
                    case "bool":%>
            <%= fieldName %> = false; <%
                        break;
                    case "decimal":
                    case "float":
                    case "byte":
                    case "short":
                    case "int":
                    case "long":%>
            <%= fieldName %> = 0; <%
                        break;
                    default:%>
            <%= fieldName %> = <% if(_useNull){ %> null; <% }
                    else {%> new <%= fieldType %>(); <% }
                    break;
                    
                    case "Guid":%> 
            <%= fieldName %>= Guid.Empty;<%
                    break;
                }
            }
        }%>
        }
        #endregion<%
    }
    
    private void BuildEqualsHashCodeOverrides( IColumns Columns )
    {
        %>#region 重写Equals和HashCode
        /// <summary>
        /// 用唯一值实现Equals
        /// </summary>
        public override bool Equals( object obj )
        {
            if( this == obj ) return true;
            if( ( obj == null ) || ( obj.GetType() != 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 )
                {
                %> &&
                (<%= ToVariableName(c.Alias) %> == castObj.<%= c.Alias %> )<%
                }
            }
        } %>;
        }
        
        /// <summary>
        /// 用唯一值实现GetHashCode
        /// </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 * <%= ToVariableName(c.Alias) %>.GetHashCode();<%
                    }
                }
                %>
            return hash; <%
            }%>
        }
        #endregion
        <%
    }
    
    private void BuildPrivateMembers( IColumns Columns )
    {
        if( Columns.Count > 0 )
        {
            %>#region 私有成员
            
        private bool <%= _prefix %>IsChanged;
        private bool <%= _prefix %>IsDeleted;<%
        
        foreach( IColumn field in Columns )
        {
            %>
        private <%= ColumnToNHibernateType( field ) %> <%= ToVariableName(field.Alias) %>; <%
        }
%>        

        #endregion<%
        }
    }
    
    private void BuildPublicAccessors( IColumns Columns )
    {
        if( Columns.Count > 0 )
        {
            %>#region 公有属性
            <%
            
            foreach( IColumn field in Columns )
            {
                string fieldAccessor = field.Alias;
                string fieldName = ToVariableName(field.Alias);
                string fieldType = ColumnToNHibernateType( field );
            %>
        /// <summary>
        /// <%= field.Description %>
        /// </summary>        
        public <%=(_enableLazyClass ? "virtual" : "")%> <%= fieldType %> <%= fieldAccessor %>
        {
            get { return <%= fieldName %>; }<%
                if( !_createReadOnly )
                {
                    //if(!((field.IsInPrimaryKey && field.IsAutoKey) || field.IsComputed))
                    //{
                        switch( fieldType )
                        {
                            default:%>
            set { <%= _prefix %>IsChanged |= (<%= fieldName %> != value); <%= fieldName %> = value; }<%                        
                                break;
                            case "byte": %>
            set    
            {
                //if( value.Length > <%= field.CharacterMaxLength.ToString() %>)
                    //throw new ArgumentOutOfRangeException("Invalid value for <%= fieldAccessor %>", value, value.ToString());
                
                <%= _prefix %>IsChanged |= (<%= fieldName %> != value); <%= fieldName %> = value;
            }
<%
                                break;
                            case "string": %>
            set    
            {
                if ( value != null)
                    if( value.Length > <%= field.CharacterMaxLength.ToString() %>)
                        throw new ArgumentOutOfRangeException("Invalid value for <%= fieldAccessor %>", value, value.ToString());
                
                <%= _prefix %>IsChanged |= (<%= fieldName %> != value); <%= fieldName %> = value;
            }<%                        
                                break;
                    }
                //}
            }%>
        }
            <%
            }
            
            %>
        /// <summary>
        /// 对象的值是否被改变
        /// </summary>
        public bool IsChanged
        {
            get { return <%= _prefix %>IsChanged; }
        }
        
        /// <summary>
        /// 对象是否已经被删除
        /// </summary>
        public bool IsDeleted
        {
            get { return <%= _prefix %>IsDeleted; }
        }
        
        #endregion <%
        }
    }
    
    private void BuildPublicFunctions( IColumns Columns )
    {%>#region 公有函数
        
        /// <summary>
        /// 标记对象已删除
        /// </summary>
        public void MarkAsDeleted()
        {
            <%= _prefix %>IsDeleted = true;
            <%= _prefix %>IsChanged = true;
        }
        
        
        #endregion<%
    }
    
    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\">";
    }
    
    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( _nameSpace ).Append( "." ).Append( _className ).Append( "," ).Append( _assembly ).Append( "\"" );
        xml.Append( " table=\"" ).Append( _tableName ).Append( "\"" );
        if(_enableLazyClass)
        {
            xml.Append( " lazy=\"true\"" );
        }
        
        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( c.Alias ).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;
                        case "Guid":
                            xml.Append( " unsaved-value=\"00000000-0000-0000-0000-000000000000\">\r\n" );
                            break;
                        default:
                            xml.Append( ">\r\n" );
                            break;
                    }
                    xml.Append( "\t\t\t<generator class=\"" );
                    xml.Append( GetGeneratorString(c));
                    xml.Append( "\"/>\r\n\t\t</id>" );
                }
            }
        }
        if( i > 1 )
        {
            xml.Append( "<composite-id access=\"field\">" );
            xml.Append( "\r\n\t\t\t" );
            foreach( IColumn c in Columns )
            {
                if( c.IsInPrimaryKey )
                {
                    xml.Append(" <key-property name=\"").Append( c.Alias ).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( " />\r\n" );
                            break;
                        default:
                            xml.Append( "/>\r\n" );
                            break;
                    }
                    xml.Append( "\t\t\t" );
                    
                }
            }
            xml.Append( "\r\n\t\t</composite-id>\r\n\t\t" );
        }
        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 !!!

                xml.Append( "<property column=\"" ).Append( c.Name );
                xml.Append( "\" type=\"" ).Append( ConvertNHibernate( ColumnToNHibernateType( c ) ) ).Append( "\"" );
                if( _createReadOnly )
                {
                    xml.Append( " access=\"field\" name=\"" ).Append( ToVariableName(c.Alias) ).Append( "\"" );
                }
                else
                {
                    xml.Append( " name=\"" ).Append( c.Alias ).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" );
                
            }
        }
        return xml.ToString();
    }
}
%>

本文由 hcb 创作,采用 知识共享署名 3.0,可自由转载、引用,但需署名作者且注明文章出处。

还不快抢沙发

添加新评论