Example #1
0
        public CodeCompileUnit GetCompileUnit(string className)
        {
            var codeGenerationHelper = new CodeGenerationHelper();
            var compileUnit          = codeGenerationHelper.GetCodeCompileUnitWithInheritanceAndInterface(nameSpace, className, appPrefs.InheritenceAndInterfaces);

            var mapper  = new DataTypeMapper();
            var newType = compileUnit.Namespaces[0].Types[0];

            newType.IsPartial = appPrefs.GeneratePartialClasses;

            CreateProperties(codeGenerationHelper, mapper, newType);

            // Generate GetHashCode() and Equals() methods.
            if (Table.PrimaryKey != null && Table.PrimaryKey.Columns.Count != 0 && Table.PrimaryKey.Type == PrimaryKeyType.CompositeKey)
            {
                var pkColsList = Table.PrimaryKey.Columns.Select(s => Formatter.FormatText(s.Name)).ToList();

                var equalsCode     = CreateCompositeKeyEqualsMethod(pkColsList);
                var getHashKeyCode = CreateCompositeKeyGetHashKeyMethod(pkColsList);

                equalsCode.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "NHibernate Composite Key Requirements"));
                newType.Members.Add(equalsCode);
                newType.Members.Add(getHashKeyCode);
                getHashKeyCode.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
            }

            // Dont create a constructor if there are no relationships.
            if (Table.HasManyRelationships.Count == 0)
            {
                return(compileUnit);
            }

            var pascalCaseTextFormatter = new PascalCaseTextFormatter {
                PrefixRemovalList = appPrefs.FieldPrefixRemovalList
            };
            var constructorStatements = new CodeStatementCollection();

            foreach (var hasMany in Table.HasManyRelationships)
            {
                if (appPrefs.Language == Language.CSharp)
                {
                    newType.Members.Add(codeGenerationHelper.CreateAutoProperty(string.Format("{0}<{1}{2}>", appPrefs.ForeignEntityCollectionType, appPrefs.ClassNamePrefix, pascalCaseTextFormatter.FormatSingular(hasMany.Reference)), Formatter.FormatPlural(hasMany.Reference), appPrefs.UseLazy));
                    constructorStatements.Add(new CodeSnippetStatement(string.Format(TABS + "{0} = new {1}<{2}{3}>();", Formatter.FormatPlural(hasMany.Reference), codeGenerationHelper.InstatiationObject(appPrefs.ForeignEntityCollectionType), appPrefs.ClassNamePrefix, pascalCaseTextFormatter.FormatSingular(hasMany.Reference))));
                }
                else if (appPrefs.Language == Language.VB)
                {
                    newType.Members.Add(codeGenerationHelper.CreateAutoProperty(string.Format("{0}(Of {1}{2})", appPrefs.ForeignEntityCollectionType, appPrefs.ClassNamePrefix, pascalCaseTextFormatter.FormatSingular(hasMany.Reference)), Formatter.FormatPlural(hasMany.Reference), appPrefs.UseLazy));
                    constructorStatements.Add(new CodeSnippetStatement(string.Format(TABS + "{0} = New {1}(Of {2}{3})()", Formatter.FormatPlural(hasMany.Reference), codeGenerationHelper.InstatiationObject(appPrefs.ForeignEntityCollectionType), appPrefs.ClassNamePrefix, pascalCaseTextFormatter.FormatSingular(hasMany.Reference))));
                }
            }

            var constructor = new CodeConstructor {
                Attributes = MemberAttributes.Public
            };

            constructor.Statements.AddRange(constructorStatements);
            newType.Members.Add(constructor);
            return(compileUnit);
        }
Example #2
0
        private void CreateAutoProperties(CodeGenerationHelper codeGenerationHelper, DataTypeMapper mapper, CodeTypeDeclaration newType)
        {
            if (Table.PrimaryKey != null)
            {
                foreach (var pk in Table.PrimaryKey.Columns)
                {
                    if (pk.IsForeignKey && appPrefs.IncludeForeignKeys)
                    {
                        newType.Members.Add(codeGenerationHelper.CreateAutoProperty(Formatter.FormatSingular(pk.ForeignKeyTableName),
                                                                                    Formatter.FormatSingular(pk.ForeignKeyTableName),
                                                                                    appPrefs.UseLazy));
                    }
                    else
                    {
                        var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, pk.DataType, pk.DataLength,
                                                                 pk.DataPrecision, pk.DataScale);
                        var fieldName   = FixPropertyWithSameClassName(pk.Name, Table.Name);
                        var pkAlsoFkQty = (from fk in Table.ForeignKeys.Where(fk => fk.UniquePropertyName == pk.Name) select fk).Count();
                        if (pkAlsoFkQty > 0)
                        {
                            fieldName = fieldName + "Id";
                        }
                        newType.Members.Add(codeGenerationHelper.CreateAutoProperty(mapFromDbType.ToString(),
                                                                                    Formatter.FormatText(fieldName),
                                                                                    appPrefs.UseLazy));
                    }
                }
            }

            if (appPrefs.IncludeForeignKeys)
            {
                var pascalCaseTextFormatter = new PascalCaseTextFormatter {
                    PrefixRemovalList = appPrefs.FieldPrefixRemovalList
                };
                // Note that a foreign key referencing a primary within the same table will end up giving you a foreign key property with the same name as the table.
                string lastOne = null;
                foreach (var fk in Table.Columns.Where(c => c.IsForeignKey && !c.IsPrimaryKey))
                {
                    var typeName     = appPrefs.ClassNamePrefix + pascalCaseTextFormatter.FormatSingular(fk.ForeignKeyTableName);
                    var propertyName = Formatter.FormatSingular(fk.ForeignKeyTableName);
                    var fieldName    = FixPropertyWithSameClassName(propertyName, Table.Name);
                    if (lastOne != fieldName)
                    {
                        newType.Members.Add(codeGenerationHelper.CreateAutoProperty(typeName, fieldName, appPrefs.UseLazy));
                    }
                    lastOne = fieldName;
                }
            }

            foreach (var column in Table.Columns.Where(x => !x.IsPrimaryKey && (!x.IsForeignKey || !appPrefs.IncludeForeignKeys)))
            {
                var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, column.DataType, column.DataLength, column.DataPrecision, column.DataScale);

                var fieldName = FixPropertyWithSameClassName(column.Name, Table.Name);
                var property  = codeGenerationHelper.CreateAutoProperty(mapFromDbType, Formatter.FormatText(fieldName), column.IsNullable, appPrefs.UseLazy);
                AttachValidatorAttributes(ref property, column);
                newType.Members.Add(property);
            }
        }
Example #3
0
        public CodeCompileUnit GetCompileUnit()
        {
            var codeGenerationHelper = new CodeGenerationHelper();
            // This is where we construct the constructor
            var compileUnit = codeGenerationHelper.GetCodeCompileUnit(nameSpace, Table.Name.GetFormattedText().MakeSingular(), true);

            var mapper  = new DataTypeMapper();
            var newType = compileUnit.Namespaces[0].Types[0];

            newType.IsPartial = applicationPreferences.GeneratePartialClasses;

            if (Table.PrimaryKey != null && Table.PrimaryKey.Columns.Count() != 0)
            {
                foreach (var pk in Table.PrimaryKey.Columns)
                {
                    var mapFromDbType = mapper.MapFromDBType(this.applicationPreferences.ServerType, pk.DataType,
                                                             pk.DataLength, pk.DataPrecision, pk.DataScale);

                    var declaration = new CodeAttributeDeclaration("PrimaryKey");
                    declaration.Arguments.Add(new CodeAttributeArgument("Column", new CodePrimitiveExpression(pk.Name)));
                    newType.Members.Add(codeGenerationHelper.CreateAutoProperty(mapFromDbType.ToString(),
                                                                                pk.Name.GetFormattedText(), declaration));
                }
            }

            foreach (var fk in Table.ForeignKeys)
            {
                newType.Members.Add(codeGenerationHelper.CreateAutoProperty(fk.References.GetFormattedText().MakeSingular(), fk.References.GetFormattedText().MakeSingular()));
            }

            foreach (var property in Table.Columns.Where(x => x.IsPrimaryKey != true && x.IsForeignKey != true))
            {
                var declaration = new CodeAttributeDeclaration("Property");
                declaration.Arguments.Add(new CodeAttributeArgument("Column", new CodePrimitiveExpression(property.Name)));

                if (property.DataLength.HasValue)
                {
                    declaration.Arguments.Add(new CodeAttributeArgument("Length", new CodePrimitiveExpression(property.DataLength)));
                }

                if (!property.IsNullable)
                {
                    declaration.Arguments.Add(new CodeAttributeArgument("NotNull", new CodePrimitiveExpression(true)));
                }

                var mapFromDbType = mapper.MapFromDBType(this.applicationPreferences.ServerType, property.DataType, property.DataLength, property.DataPrecision, property.DataScale);
                newType.Members.Add(codeGenerationHelper.CreateAutoProperty(mapFromDbType.ToString(), property.Name.GetFormattedText(), declaration));
            }

            return(compileUnit);
        }
Example #4
0
        public CodeCompileUnit GetCompileUnit()
        {
            var codeGenerationHelper = new CodeGenerationHelper();
            // This is where we construct the constructor
            var compileUnit = codeGenerationHelper.GetCodeCompileUnit(nameSpace, Table.Name.GetFormattedText().MakeSingular(),true);

            var mapper = new DataTypeMapper();
            var newType = compileUnit.Namespaces[0].Types[0];
            newType.IsPartial = applicationPreferences.GeneratePartialClasses;

            if (Table.PrimaryKey != null && Table.PrimaryKey.Columns.Count() != 0)
            {
                foreach (var pk in Table.PrimaryKey.Columns)
                {
                    var mapFromDbType = mapper.MapFromDBType(this.applicationPreferences.ServerType, pk.DataType,
                                                             pk.DataLength, pk.DataPrecision, pk.DataScale);

                    var declaration = new CodeAttributeDeclaration("PrimaryKey");
                    declaration.Arguments.Add(new CodeAttributeArgument("Column", new CodePrimitiveExpression(pk.Name)));
                    newType.Members.Add(codeGenerationHelper.CreateAutoProperty(mapFromDbType.ToString(),
                                                                                pk.Name.GetFormattedText(), declaration));
                }
            }

            foreach (var fk in Table.ForeignKeys)
            {
                newType.Members.Add(codeGenerationHelper.CreateAutoProperty(fk.References.GetFormattedText().MakeSingular(), fk.References.GetFormattedText().MakeSingular()));
            }

            foreach (var property in Table.Columns.Where(x => x.IsPrimaryKey != true && x.IsForeignKey != true))
            {
                var declaration = new CodeAttributeDeclaration("Property");
                declaration.Arguments.Add(new CodeAttributeArgument("Column", new CodePrimitiveExpression(property.Name)));

                if(property.DataLength.HasValue)
                    declaration.Arguments.Add(new CodeAttributeArgument("Length", new CodePrimitiveExpression(property.DataLength)));

                if (!property.IsNullable)
                {
                    declaration.Arguments.Add(new CodeAttributeArgument("NotNull", new CodePrimitiveExpression(true)));
                }

                var mapFromDbType = mapper.MapFromDBType(this.applicationPreferences.ServerType, property.DataType, property.DataLength, property.DataPrecision, property.DataScale);
                newType.Members.Add(codeGenerationHelper.CreateAutoProperty(mapFromDbType.ToString(), property.Name.GetFormattedText(), declaration));
            }

            return compileUnit;
        }
Example #5
0
        public CodeCompileUnit GetCompileUnit(string className)
        {
            var codeGenerationHelper = new CodeGenerationHelper();
            var compileUnit          = codeGenerationHelper.GetCodeCompileUnitWithInheritanceAndInterface(nameSpace, className, appPrefs.InheritenceAndInterfaces);

            var mapper  = new DataTypeMapper();
            var newType = compileUnit.Namespaces[0].Types[0];

            newType.IsPartial = appPrefs.GeneratePartialClasses;

            CreateProperties(codeGenerationHelper, mapper, newType);

            var constructorStatements = new CodeStatementCollection();

            foreach (var hasMany in Table.HasManyRelationships)
            {
                newType.Members.Add(codeGenerationHelper.CreateAutoProperty(appPrefs.ForeignEntityCollectionType + "<" + appPrefs.ClassNamePrefix + Formatter.FormatSingular(hasMany.Reference) + ">", "Lista" + Formatter.FormatSingular(hasMany.Reference), appPrefs.UseLazy));
                //constructorStatements.Add(new CodeSnippetStatement(string.Format(TABS + "{0} = new {1}<{2}{3}>();", Formatter.FormatPlural(hasMany.Reference), codeGenerationHelper.InstatiationObject(appPrefs.ForeignEntityCollectionType), appPrefs.ClassNamePrefix, Formatter.FormatSingular(hasMany.Reference))));
            }

            var constructor = new CodeConstructor {
                Attributes = MemberAttributes.Public
            };

            constructor.Statements.AddRange(constructorStatements);
            newType.Members.Add(constructor);
            return(compileUnit);
        }
Example #6
0
        private void CreateAutoProperties(CodeGenerationHelper codeGenerationHelper, DataTypeMapper mapper, CodeTypeDeclaration newType)
        {
            if (Table.PrimaryKey != null)
            {
                foreach (var pk in Table.PrimaryKey.Columns)
                {
                    var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, pk.DataType, pk.DataLength,
                                                             pk.DataPrecision, pk.DataScale);
                    newType.Members.Add(codeGenerationHelper.CreateAutoProperty(mapFromDbType.ToString(),
                                                                                Formatter.FormatText(pk.Name),
                                                                                appPrefs.UseLazy));
                }
            }

            if (appPrefs.IncludeForeignKeys)
            {
                var pascalCaseTextFormatter = new PascalCaseTextFormatter {
                    PrefixRemovalList = appPrefs.FieldPrefixRemovalList
                };
                // Note that a foreign key referencing a primary within the same table will end up giving you a foreign key property with the same name as the table.
                foreach (var fk in Table.ForeignKeys.Where(fk => !string.IsNullOrEmpty(fk.References)))
                {
                    var typeName = appPrefs.ClassNamePrefix + pascalCaseTextFormatter.FormatSingular(fk.References);
                    newType.Members.Add(codeGenerationHelper.CreateAutoProperty(typeName, Formatter.FormatSingular(fk.UniquePropertyName), appPrefs.UseLazy));
                }
            }

            foreach (var column in Table.Columns.Where(x => !x.IsPrimaryKey && (!x.IsForeignKey || !appPrefs.IncludeForeignKeys)))
            {
                var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, column.DataType, column.DataLength, column.DataPrecision, column.DataScale);

                var property = codeGenerationHelper.CreateAutoProperty(mapFromDbType, Formatter.FormatText(column.Name), column.IsNullable, appPrefs.UseLazy);
                AttachValidatorAttributes(ref property, column);
                newType.Members.Add(property);
            }
        }
Example #7
0
        private void CreateAutoProperties(CodeGenerationHelper codeGenerationHelper, DataTypeMapper mapper, CodeTypeDeclaration newType)
        {
            foreach (var pk in Table.PrimaryKey.Columns)
            {
                var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, pk.DataType, pk.DataLength, pk.DataPrecision, pk.DataScale);
                newType.Members.Add(codeGenerationHelper.CreateAutoProperty(mapFromDbType.ToString(), Formatter.FormatText(pk.Name), appPrefs.UseLazy));
            }

            // Note that a foreign key referencing a primary within the same table will end up giving you a foreign key property with the same name as the table.
            foreach (var fk in Table.ForeignKeys.Where(fk => !string.IsNullOrEmpty(fk.References)))
            {
                newType.Members.Add(codeGenerationHelper.CreateAutoProperty(appPrefs.ClassNamePrefix + Formatter.FormatSingular(fk.References) + "DTO", Formatter.FormatSingular(fk.UniquePropertyName), appPrefs.UseLazy));
            }

            foreach (var column in Table.Columns.Where(x => x.IsPrimaryKey != true))
            {
                if (!appPrefs.IncludeForeignKeys && column.IsForeignKey)
                {
                    continue;
                }
                var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, column.DataType, column.DataLength, column.DataPrecision, column.DataScale);
                newType.Members.Add(codeGenerationHelper.CreateAutoProperty(mapFromDbType, Formatter.FormatText(column.Name), column.IsNullable, appPrefs.UseLazy));
            }
        }
 public void ShouldGenerateAutoProperty()
 {
     var codeGenerationHelper = new CodeGenerationHelper();
     CodeMemberProperty autoProperty = codeGenerationHelper.CreateAutoProperty(typeof (string), "Name", false);
     CodeCompileUnit codeCompileUnit = codeGenerationHelper.GetCodeCompileUnit("someNamespace", "someType");
     codeCompileUnit.Namespaces[0].Types[0].Members.Add(autoProperty);
     cSharpCodeProvider.GenerateCodeFromCompileUnit(codeCompileUnit, new StringWriter(stringBuilder),
                                                    new CodeGeneratorOptions());
     var builderCompare = new StringBuilder();
     builderCompare.AppendLine("public virtual string Name {");
     builderCompare.AppendLine("            get {");
     builderCompare.AppendLine("            }");
     builderCompare.AppendLine("            set {");
     builderCompare.AppendLine("            }");
     builderCompare.Append("        }");
     Assert.IsTrue(stringBuilder.ToString().Contains(builderCompare.ToString()));
 }
Example #9
0
        public CodeCompileUnit GetCompileUnit(string className)
        {
            var codeGenerationHelper = new CodeGenerationHelper();
            var compileUnit = codeGenerationHelper.GetCodeCompileUnitWithInheritanceAndInterface(nameSpace, className, appPrefs.InheritenceAndInterfaces);

            var mapper = new DataTypeMapper();
            var newType = compileUnit.Namespaces[0].Types[0];

            newType.IsPartial = appPrefs.GeneratePartialClasses;

            CreateProperties(codeGenerationHelper, mapper, newType);

            // Generate GetHashCode() and Equals() methods.
            if (Table.PrimaryKey != null && Table.PrimaryKey.Columns.Count != 0 && Table.PrimaryKey.Type == PrimaryKeyType.CompositeKey)
            {
                var pkColsList = new List<string>();
                foreach (var pkCol in Table.PrimaryKey.Columns)
                {
                    if (pkCol.IsForeignKey && appPrefs.IncludeForeignKeys)
                    {
                        pkColsList.Add(Formatter.FormatSingular(pkCol.ForeignKeyTableName) + "." + Formatter.FormatText(pkCol.ForeignKeyColumnName));
                    }
                    else
                    {
                        pkColsList.Add(Formatter.FormatText(pkCol.Name));
                    }
                }

                var equalsCode = CreateCompositeKeyEqualsMethod(pkColsList);
                var getHashKeyCode = CreateCompositeKeyGetHashKeyMethod(pkColsList);

                equalsCode.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "NHibernate Composite Key Requirements"));
                newType.Members.Add(equalsCode);
                newType.Members.Add(getHashKeyCode);
                getHashKeyCode.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));
            }

            // Dont create a constructor if there are no relationships.
            if (Table.HasManyRelationships.Count == 0)
                return compileUnit;

            var pascalCaseTextFormatter = new PascalCaseTextFormatter { PrefixRemovalList = appPrefs.FieldPrefixRemovalList };
            var constructorStatements = new CodeStatementCollection();
            if (appPrefs.IncludeHasMany)
                foreach (var hasMany in Table.HasManyRelationships)
                {

                    if (appPrefs.Language == Language.CSharp)
                    {
                        newType.Members.Add(codeGenerationHelper.CreateAutoProperty(string.Format("{0}<{1}{2}>", appPrefs.ForeignEntityCollectionType, appPrefs.ClassNamePrefix, pascalCaseTextFormatter.FormatSingular(hasMany.Reference)), Formatter.FormatPlural(hasMany.Reference), appPrefs.UseLazy));
                        constructorStatements.Add(new CodeSnippetStatement(string.Format(TABS + "{0} = new {1}<{2}{3}>();", Formatter.FormatPlural(hasMany.Reference), codeGenerationHelper.InstatiationObject(appPrefs.ForeignEntityCollectionType), appPrefs.ClassNamePrefix, pascalCaseTextFormatter.FormatSingular(hasMany.Reference))));
                    } else if (appPrefs.Language == Language.VB)
                    {
                        newType.Members.Add(codeGenerationHelper.CreateAutoProperty(string.Format("{0}(Of {1}{2})", appPrefs.ForeignEntityCollectionType, appPrefs.ClassNamePrefix, pascalCaseTextFormatter.FormatSingular(hasMany.Reference)), Formatter.FormatPlural(hasMany.Reference), appPrefs.UseLazy));
                        constructorStatements.Add(new CodeSnippetStatement(string.Format(TABS + "{0} = New {1}(Of {2}{3})()", Formatter.FormatPlural(hasMany.Reference), codeGenerationHelper.InstatiationObject(appPrefs.ForeignEntityCollectionType), appPrefs.ClassNamePrefix, pascalCaseTextFormatter.FormatSingular(hasMany.Reference))));
                    }
                }

            var constructor = new CodeConstructor { Attributes = MemberAttributes.Public };
            constructor.Statements.AddRange(constructorStatements);
            newType.Members.Add(constructor);
            return compileUnit;
        }
Example #10
0
        private void CreateAutoProperties(CodeGenerationHelper codeGenerationHelper, DataTypeMapper mapper, CodeTypeDeclaration newType)
        {
            if (Table.PrimaryKey != null)
            {
                foreach (var pk in Table.PrimaryKey.Columns)
                {
                    if (pk.IsForeignKey && appPrefs.IncludeForeignKeys)
                    {
                        newType.Members.Add(codeGenerationHelper.CreateAutoProperty(Formatter.FormatSingular(pk.ForeignKeyTableName),
                                                                                    Formatter.FormatSingular(pk.ForeignKeyTableName),
                                                                                    appPrefs.UseLazy));
                    }
                    else
                    {
                        var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, pk.DataType, pk.DataLength,
                                                             pk.DataPrecision, pk.DataScale);
                        var fieldName = FixPropertyWithSameClassName(pk.Name, Table.Name);
                        var pkAlsoFkQty = (from fk in Table.ForeignKeys.Where(fk => fk.UniquePropertyName == pk.Name) select fk).Count();
                        if (pkAlsoFkQty > 0)
                            fieldName = fieldName + "Id";
                        newType.Members.Add(codeGenerationHelper.CreateAutoProperty(mapFromDbType.ToString(),
                                                                                Formatter.FormatText(fieldName),
                                                                                appPrefs.UseLazy));
                    }
                }
            }

            if (appPrefs.IncludeForeignKeys)
            {
                var pascalCaseTextFormatter = new PascalCaseTextFormatter { PrefixRemovalList = appPrefs.FieldPrefixRemovalList };
                // Note that a foreign key referencing a primary within the same table will end up giving you a foreign key property with the same name as the table.
                string lastOne = null;
                foreach (var fk in Table.Columns.Where(c => c.IsForeignKey && !c.IsPrimaryKey))
                {
                    var typeName = appPrefs.ClassNamePrefix + pascalCaseTextFormatter.FormatSingular(fk.ForeignKeyTableName);
                    var propertyName = Formatter.FormatSingular(fk.ForeignKeyTableName);
                    var fieldName = FixPropertyWithSameClassName(propertyName, Table.Name);
                    if (lastOne != fieldName)
                        newType.Members.Add(codeGenerationHelper.CreateAutoProperty(typeName, fieldName, appPrefs.UseLazy));
                    lastOne = fieldName;
                }
            }

            foreach (var column in Table.Columns.Where(x => !x.IsPrimaryKey && (!x.IsForeignKey || !appPrefs.IncludeForeignKeys)))
            {
                var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, column.DataType, column.DataLength, column.DataPrecision, column.DataScale);

                var fieldName = FixPropertyWithSameClassName(column.Name, Table.Name);
                var property = codeGenerationHelper.CreateAutoProperty(mapFromDbType, Formatter.FormatText(fieldName), column.IsNullable, appPrefs.UseLazy);
                AttachValidatorAttributes(ref property, column);
                newType.Members.Add(property);
            }
        }
Example #11
0
        public CodeCompileUnit GetCompileUnit(out CodeCompileUnit pkClass)
        {
            var codeGenerationHelper = new CodeGenerationHelper();
            var compileUnit = codeGenerationHelper.GetCodeCompileUnit(nameSpace, tableName.GetFormattedText());
            CodeCompileUnit pkCompileUnit = null;
            var mapper = new DataTypeMapper();
            var newType = compileUnit.Namespaces[0].Types[0];
            List<ColumnDetail> pkColumns = columnDetails.FindAll(col => col.IsPrimaryKey);
            List<ColumnDetail> normalColumns = columnDetails.FindAll(col => col.IsPrimaryKey == false);

            // data contract count
            int dataContractCount = 1;

            // create pk columns
            if(pkColumns.Count > 0)
            {
                if(pkColumns.Count == 1)
                {
                    var columnDetail = pkColumns[0];
                    string propertyName = columnDetail.ColumnName.GetPreferenceFormattedText(applicationPreferences);
                    Type mapFromDbType = mapper.MapFromDBType(columnDetail.DataType, columnDetail.DataLength, columnDetail.DataPrecision, columnDetail.DataScale);

                    switch (applicationPreferences.FieldGenerationConvention)
                    {
                        case FieldGenerationConvention.Property:
                            newType.Members.Add(codeGenerationHelper.CreateProperty(mapFromDbType, propertyName.MakeFirstCharUpperCase()));
                            newType.Members.Add(codeGenerationHelper.CreateField(mapFromDbType, propertyName.MakeFirstCharLowerCase()));
                            break;
                        case FieldGenerationConvention.AutoProperty:
                            propertyName = columnDetail.ColumnName.GetFormattedText();
                            var codeMemberProperty = codeGenerationHelper.CreateAutoProperty(mapFromDbType, propertyName);
                            newType.Members.Add(codeMemberProperty);
                            break;
                        default:
                            newType.Members.Add(codeGenerationHelper.CreateField(mapFromDbType, propertyName));
                            break;
                    }
                }
                else // composite key
                {
                    string pkClassName = tableName.GetFormattedText() + "PK";
                    string pkRefProperty = pkClassName;
                    pkCompileUnit = codeGenerationHelper.GetCodeCompileUnit(nameSpace, pkClassName);
                    var newPKType = pkCompileUnit.Namespaces[0].Types[0];

                    // create composite member
                    switch (applicationPreferences.FieldGenerationConvention)
                    {
                        case FieldGenerationConvention.Property:
                            newType.Members.Add(codeGenerationHelper.CreateProperty(pkClassName, pkRefProperty.MakeFirstCharUpperCase()));
                            newType.Members.Add(codeGenerationHelper.CreateField(pkClassName, pkRefProperty.MakeFirstCharLowerCase()));
                            break;
                        case FieldGenerationConvention.AutoProperty:
                            //pkPropertyName = columnDetail.ColumnName.GetFormattedText();
                            var codeMemberProperty = codeGenerationHelper.CreateAutoProperty(pkClassName, pkRefProperty);
                            newType.Members.Add(codeMemberProperty);
                            break;
                        default:
                            newType.Members.Add(codeGenerationHelper.CreateField(pkClassName, pkRefProperty));
                            break;
                    }

                    // create pk columns
                    foreach (var columnDetail in pkColumns)
                    {
                        string pkPropertyName = columnDetail.ColumnName.GetPreferenceFormattedText(applicationPreferences);
                        Type pkMapFromDbType = mapper.MapFromDBType(columnDetail.DataType, columnDetail.DataLength, columnDetail.DataPrecision, columnDetail.DataScale);

                        // get compile unit of compile class
                        switch (applicationPreferences.FieldGenerationConvention)
                        {
                            case FieldGenerationConvention.Property:
                                newPKType.Members.Add(codeGenerationHelper.CreateProperty(pkMapFromDbType, pkPropertyName.MakeFirstCharUpperCase()));
                                newPKType.Members.Add(codeGenerationHelper.CreateField(pkMapFromDbType, pkPropertyName.MakeFirstCharLowerCase()));
                                break;
                            case FieldGenerationConvention.AutoProperty:
                                pkPropertyName = columnDetail.ColumnName.GetFormattedText();
                                var codeMemberProperty = codeGenerationHelper.CreateAutoProperty(pkMapFromDbType, pkPropertyName);
                                newPKType.Members.Add(codeMemberProperty);
                                break;
                            default:
                                newPKType.Members.Add(codeGenerationHelper.CreateField(pkMapFromDbType, pkPropertyName));
                                break;
                        }
                    }

                    newPKType.CustomAttributes.Add(new CodeAttributeDeclaration("Serializable"));
                    newPKType.CustomAttributes.Add(new CodeAttributeDeclaration("Validate"));
                    newPKType.CustomAttributes.Add(new CodeAttributeDeclaration("DataContract"));
                    foreach (var member in newPKType.Members)
                    {
                        if (member is CodeMemberProperty)
                        {
                            CodeMemberProperty property = (CodeMemberProperty)member;
                            CodeAttributeArgument[] arguments =
                                new CodeAttributeArgument[]
                         {
                            new CodeAttributeArgument("Name",new CodePrimitiveExpression(dataContractCount.ToString())),
                            new CodeAttributeArgument("Order",new CodePrimitiveExpression(dataContractCount++))
                         };
                            property.CustomAttributes.Add(new CodeAttributeDeclaration("DataMember", arguments));
                        }
                    }
                }
            }

            // create normal columns
            foreach (var columnDetail in normalColumns)
            {
                string propertyName = columnDetail.ColumnName.GetPreferenceFormattedText(applicationPreferences);
                Type mapFromDbType = mapper.MapFromDBType(columnDetail.DataType, columnDetail.DataLength, columnDetail.DataPrecision, columnDetail.DataScale);
                if(FiendInTableReference(columnDetail)) continue;
                switch (applicationPreferences.FieldGenerationConvention)
                {
                    case FieldGenerationConvention.Property:
                        newType.Members.Add(codeGenerationHelper.CreateProperty(mapFromDbType, propertyName.MakeFirstCharUpperCase()));
                        newType.Members.Add(codeGenerationHelper.CreateField(mapFromDbType, propertyName.MakeFirstCharLowerCase()));
                        break;
                    case FieldGenerationConvention.AutoProperty:
                        propertyName = columnDetail.ColumnName.GetFormattedText();
                        var codeMemberProperty = codeGenerationHelper.CreateAutoProperty(mapFromDbType, propertyName);
                        newType.Members.Add(codeMemberProperty);
                        break;
                    default:
                        newType.Members.Add(codeGenerationHelper.CreateField(mapFromDbType, propertyName));
                        break;
                }
            }

            // create detail member if exist
            if(tableReferences != null && tableReferences.Count > 0)
            {
                foreach (KeyValuePair<string, TableReference> pair in tableReferences)
                {
                    TableReference reference = pair.Value;
                    string refTable = GlobalCache.Instance.ReplaceShortWords(reference.ReferenceTable);
                    switch(reference.ReferenceType)
                    {
                        case ReferenceType.OneToMany:
                            refTable = refTable.GetFormattedText();
                            var detailListMemberProperty = codeGenerationHelper.CreateAutoProperty("IList<" + refTable + ">", refTable + "s");
                            newType.Members.Add(detailListMemberProperty);
                            break;
                        case ReferenceType.ManyToOne:
                            refTable = refTable.GetFormattedText();
                            var masterMemberProperty = codeGenerationHelper.CreateAutoProperty(refTable, refTable);
                            newType.Members.Add(masterMemberProperty);
                            break;
                    }
                }
            }

            var constructor = new CodeConstructor {Attributes = MemberAttributes.Public};
            newType.Members.Add(constructor);
            newType.CustomAttributes.Add(new CodeAttributeDeclaration("Serializable"));
            newType.CustomAttributes.Add(new CodeAttributeDeclaration("Validate"));
            newType.CustomAttributes.Add(new CodeAttributeDeclaration("DataContract"));
            foreach (var member in newType.Members)
            {
                if(member is CodeMemberProperty)
                {
                    CodeMemberProperty property = (CodeMemberProperty) member;
                    CodeAttributeArgument[] arguments =
                        new CodeAttributeArgument[]
                         {
                            new CodeAttributeArgument("Name",new CodePrimitiveExpression(dataContractCount.ToString())),
                            new CodeAttributeArgument("Order",new CodePrimitiveExpression(dataContractCount++))
                         };
                    property.CustomAttributes.Add(new CodeAttributeDeclaration("DataMember",arguments));
                }
            }

            pkClass = pkCompileUnit;
            return compileUnit;
        }
Example #12
0
        private void CreateAutoProperties(CodeGenerationHelper codeGenerationHelper, DataTypeMapper mapper, CodeTypeDeclaration newType)
        {
            if (Table.PrimaryKey != null)
            {
                foreach (var pk in Table.PrimaryKey.Columns)
                {
                    var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, pk.DataType, pk.DataLength,
                                                             pk.DataPrecision, pk.DataScale);
                    newType.Members.Add(codeGenerationHelper.CreateAutoProperty(mapFromDbType.ToString(),
                                                                                Formatter.FormatText(pk.Name),
                                                                                appPrefs.UseLazy));
                }
            }

            if (appPrefs.IncludeForeignKeys)
            {
                var pascalCaseTextFormatter = new PascalCaseTextFormatter { PrefixRemovalList = appPrefs.FieldPrefixRemovalList };
                // Note that a foreign key referencing a primary within the same table will end up giving you a foreign key property with the same name as the table.
                foreach (var fk in Table.ForeignKeys.Where(fk => !string.IsNullOrEmpty(fk.References)))
                {
                    var typeName = appPrefs.ClassNamePrefix + pascalCaseTextFormatter.FormatSingular(fk.References);
                    newType.Members.Add(codeGenerationHelper.CreateAutoProperty(typeName, Formatter.FormatSingular(fk.UniquePropertyName), appPrefs.UseLazy));
                }
            }

            foreach (var column in Table.Columns.Where(x => !x.IsPrimaryKey && (!x.IsForeignKey || !appPrefs.IncludeForeignKeys)))
            {
                var mapFromDbType = mapper.MapFromDBType(this.appPrefs.ServerType, column.DataType, column.DataLength, column.DataPrecision, column.DataScale);

                var property = codeGenerationHelper.CreateAutoProperty(mapFromDbType, Formatter.FormatText(column.Name), column.IsNullable, appPrefs.UseLazy);
                AttachValidatorAttributes(ref property, column);
                newType.Members.Add(property);
            }
        }