Click here to Skip to main content
15,897,371 members
Articles / Web Development / ASP.NET

NHibernate Templates for Smart Code Generator

Rate me:
Please Sign up or sign in to vote.
4.77/5 (20 votes)
11 Dec 2007CPOL5 min read 206.8K   1.9K   130  
Describes how to generate NHibernate objects and ASPX pages using Smart Code
using System;
using System.Collections.Generic;
using System.Text;
using SmartCode.Template;
using SmartCode.Model;

namespace NHibernateTemplates
{
    public class NHibernateClass: TemplateBase
    {
        public NHibernateClass()
        {
            CreateOutputFile = true;
            Description = "Generates a C# class for use with NHibernate";
            Name = "Class File";
            OutputFolder = "NHibernate/Domain";
        }

        public override string OutputFileName()
        {
            return Helper.ClassName(Entity.Code) + ".cs";
        }

        public override void ProduceCode()
        {
            IList<ColumnSchema> primaryKeyColumns = Table.PrimaryKeyColumns();
 
            if (primaryKeyColumns.Count > 0)
            {
                WriteLine(@"using System;");
                WriteLine(@"using System.Collections.Generic;");
                WriteLine(@"");
                WriteLine(@"namespace {0}.Core.Domain", Helper.PascalCase(Domain.Code));

                WriteLine(@"{");
                WriteLine(@"    /// <summary>");
                WriteLine(@"    /// {0} object for NHibernate mapped table {1}.", Helper.ClassName(Entity.Code), Entity.Name);
                WriteLine(@"    /// </summary>");

                WriteLine(@"    [Serializable]");
                if (primaryKeyColumns.Count > 1)
                {
                    WriteLine(@"    public class {0} : DomainObject<{0}.DomainObjectID>", Helper.ClassName(Entity.Code));
                }
                else
                {
                    WriteLine(@"    public class {0} : DomainObject<{1}>", Helper.ClassName(Entity.Code), primaryKeyColumns[0].NetDataType );
                } 
                WriteLine(@"    {");
                WriteLine(@"");

                if (primaryKeyColumns.Count > 1)
                {
                    WriteLine(@"        [Serializable]");
                    WriteLine(@"        public class DomainObjectID");
                    WriteLine(@"        {");
                    WriteLine(@"            public DomainObjectID() {}");
                    W();
                    string hashCode = "";
                    string constArguments = "";

                    foreach (ColumnSchema column in primaryKeyColumns)
                    {
                        WriteLine(@"            private {0} _{1};", column.NetDataType, column.Code);
                        if (hashCode != "")
                        {
                            hashCode += " ^ ";
                            constArguments += ", ";
                        }
                        hashCode += String.Format("{0}.GetHashCode()", column.Code);
                        constArguments += String.Format("{0} {1}", column.NetDataType, Helper.CamelCase(column.Code));
                    }
                    W();
                    //Agreguemos el constructor, sino perderemos horas y horas viendo por que no carga la joda esta

                    WriteLine(@"            public DomainObjectID(" + constArguments + ")");
                    WriteLine(@"            {");
                    foreach (ColumnSchema column in primaryKeyColumns)
                    {
                        WriteLine(@"                _{0} = {1};", column.Code, Helper.CamelCase(column.Code));
                    }
                    WriteLine(@"            }");

                    W();
                    foreach (ColumnSchema column in primaryKeyColumns)
                    {

                        WriteLine("         public " + column.NetDataType + " " + column.Code + " {");
                        WriteLine("             get { return _" + column.Code + "; }");
                        WriteLine("             protected set { _" + column.Code + " = value;}");
                        WriteLine("         }");
                        W();
                    }
                    W();
                    WriteLine(@"         public override bool Equals(object obj)");
                    WriteLine(@"         {");
                    WriteLine(@"             if (obj == this) return true;");
                    WriteLine(@"             if (obj == null) return false;");
                    W();
                    WriteLine(@"             DomainObjectID that = obj as DomainObjectID;");
                    WriteLine(@"             if (that == null)");
                    WriteLine(@"             {");
                    WriteLine(@"                 return false;");
                    WriteLine(@"             }");
                    WriteLine(@"             else");
                    WriteLine(@"             {");
                    foreach (ColumnSchema column in primaryKeyColumns)
                    {
                        WriteLine(@"                 if (this.{0} != that.{0}) return false;", column.Code);
                    }
                    W();
                    WriteLine(@"                 return true;");
                    WriteLine(@"             }");
                    W();
                    WriteLine(@"         }");
                    W();
                    WriteLine(@"            public override int GetHashCode()");
                    WriteLine(@"            {");
                    WriteLine(@"                return {0};", hashCode);
                    WriteLine(@"            }");
                    W();
                    WriteLine(@"        }");
                }
                W();


                foreach (ColumnSchema column in Table.NoPrimaryKeyColumns())
                {
                    if (Helper.IsNullableType(column) && column.NetDataType != "System.Byte[]")
                            WriteLine(@"        private {0}? _{1};", column.NetDataType, column.Code);
                    else
                        WriteLine(@"        private {0} _{1};", column.NetDataType, column.Code);
                }

                foreach (ReferenceSchema inReference in Table.InReferences)
                {
                    foreach (ReferenceJoin join in inReference.Joins)
                    {
                        string propertyName = Helper.PascalCase(join.ChildColumn.Code + "_" + inReference.ParentTable.Code);
                        WriteLine(@"        private {0} _{1};", Helper.ClassName(inReference.ParentTable.Code), propertyName);
                    }
                }

                foreach (ReferenceSchema outReference in Table.OutReferences)
                {
                    TableSchema childTable = outReference.ChildTable;

                    if (!Helper.IsManyToManyTable(childTable))
                    {
                        WriteLine(@"        private IList<{0}> _{1} = new List<{0}>();", Helper.ClassName(childTable.Code), Helper.MakePlural(childTable.Code));
                    }
                    else
                    {
                        ReferenceSchema parentSchema = childTable.InReferences[1];

                        if (parentSchema.ParentTable.ObjectID == Table.ObjectID)
                        {
                            parentSchema = childTable.InReferences[0];
                        }

                        WriteLine(@"        private IList<{0}> _{1} = new List<{0}>();", Helper.ClassName(childTable.Code), Helper.MakePlural(parentSchema.ParentTable.Code));
                    }
                }
                W();
                //Constructor
                WriteLine(@"        public {0}()", Helper.ClassName(Entity.Code));
                WriteLine(@"        {");          
                WriteLine(@"        }");
                W();
                if (primaryKeyColumns.Count > 1)
                {
                    WriteLine(@"        public {0}(DomainObjectID id)", Helper.ClassName(Entity.Code));
                }
                else
                {
                    WriteLine(@"        public {0}({1} id)", Helper.ClassName(Entity.Code), primaryKeyColumns[0].NetDataType);
                }
                WriteLine(@"        {");
                WriteLine(@"            base.id = id;");
                WriteLine(@"        }");
                W();
                //Properties
                //Read-only PKs
                if (primaryKeyColumns.Count > 1)
                {
                    foreach (ColumnSchema column in primaryKeyColumns)
                    {
                        WriteLine("         public virtual " + column.NetDataType + " " + column.Code + " {");
                        WriteLine("             get { return base.id." + column.Code + "; }");
                        WriteLine("         }");
                        W();
                    }
                }

                foreach (ColumnSchema column in Table.NoPrimaryKeyColumns())
                {
                    if (Helper.IsNullableType(column) && column.NetDataType != "System.Byte[]")
                            WriteLine("         public virtual " + column.NetDataType + "? " + column.Code + " {");
                    else
                        WriteLine("         public virtual " + column.NetDataType + " " + column.Code + " {");
                    WriteLine("             get { return _" + column.Code + "; }");
                    WriteLine("             set { _" + column.Code + " = value;}");
                    WriteLine("         }");
                    W();
                }

                foreach (ReferenceSchema inReference in Table.InReferences)
                {
                    foreach (ReferenceJoin join in inReference.Joins)
                    {
                        string propertyName = Helper.PascalCase(join.ChildColumn.Code + "_" + inReference.ParentTable.Code);

                        WriteLine("         public virtual " + Helper.ClassName(inReference.ParentTable.Code) + " " + propertyName + "{");
                        WriteLine("             get { return _" + propertyName + "; }");
                        WriteLine("             set { _" + propertyName + " = value;}");
                        WriteLine("         }");
                        W();
                    }
                }

                foreach (ReferenceSchema outReference in Table.OutReferences)
                {
                    TableSchema childTable = outReference.ChildTable;

                    if (!Helper.IsManyToManyTable(childTable))
                    {
                        WriteLine("         public virtual IList<" + Helper.ClassName(childTable.Code) + "> " + Helper.MakePlural(childTable.Code) + "{");
                        WriteLine("             get { return _" + Helper.MakePlural(childTable.Code) + "; }");
                        WriteLine("             set { _" + Helper.MakePlural(childTable.Code) + " = value; }");
                        WriteLine("         }");
                        W();

                    }
                    else
                    {
                        ReferenceSchema parentSchema = childTable.InReferences[1];

                        if (parentSchema.ParentTable.ObjectID == Table.ObjectID)
                        {
                            parentSchema = childTable.InReferences[0];
                        }
                        WriteLine("         public virtual IList<" + Helper.ClassName(childTable.Code) + "> " + Helper.MakePlural(parentSchema.ParentTable.Code) + "{");
                        WriteLine("             get { return _" + Helper.MakePlural(parentSchema.ParentTable.Code) + "; }");
                        WriteLine("             set { _" + Helper.MakePlural(parentSchema.ParentTable.Code) + " = value; }");
                        WriteLine("         }");
                        W();

                    }
                }
                WriteLine(@"");
                WriteLine(@"        public override int GetHashCode()");
                WriteLine(@"        {");
                WriteLine(@"            return ID.GetHashCode();");
                WriteLine(@"        }");
                WriteLine(@"");


                WriteLine("     }");
                WriteLine("}");
     
            }
            else
            {
                WriteLine("//-- Entity " + Entity.Name + " has no primary key information.");
            }   
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
Danilo is the creator of SmartRules, a Business Rules Engine. He is an industry consultant working primarily with companies interested in implementing dynamic rules programming concepts to add flexibility to their architectures on web, CE, and desktop platforms. He operates his own website, Kontac, where you will find more information.

To contact Danilo, email him at danilo.mendez@gmail.com.

Comments and Discussions