Beispiel #1
0
        /// <summary>
        /// These mapping configuration methods are obsolete-ish because recent EntityFramework
        /// versions don't use MappingConfiguration classes anymore. Still, leaving in for
        /// backwards compatibility.
        /// </summary>
        /// <param name="classConfiguration"></param>
        protected string BeginMappingConfigurationClass(ClassConfiguration configuration, bool isPartial = false)
        {
            this._builder.Clear();
            string newClassName = this._builder.ClassNameNewNameMappings.ContainsKey(configuration.ClassName)
                ? this._builder.ClassNameNewNameMappings[configuration.ClassName]
                : configuration.ClassName;

            this._builder
            .WriteLine("using System.Data.Entity.ModelConfiguration;")
            .WriteUsingNamespaces()
            .WriteLine()
            .WriteNamespaceDeclaration(configuration.EntityNamespace + ".Mappings");
            if (isPartial == true)
            {
                this._builder
                .WriteLine("/* This file is for hand-written custom relationships and navigation properties;")
                .WriteLine($" *  edit this file only, not the corresponding .cs file. */");
            }
            else
            {
                this._builder
                .WriteLine("/* This file was created by a generator; do not edit it directly. In order to add")
                .WriteLine(" *\trelationships and navigation properties, use the corresponding .partial.cs file. */");
            }
            _builder.WriteClassDeclaration(className: newClassName + "Mapping", inherits: "EntityTypeConfiguration<" + newClassName + ">", implementsInterfaces: null, classAttributes: _options.MappingAttributes);
            return(newClassName);
        }
Beispiel #2
0
        public void CreateBusinessObjectClass(ClassConfiguration classConfiguration, string tableName)
        {
            var    businessObjectOutputDirectoryPath = GetBusinessObjectsOutputDirectory(classConfiguration);
            var    businessObjectNamespace           = GetBusinessObjectNamespace();
            string innerNamespace = GetInnerNamespace(tableName);
            var    fullNamespace  = innerNamespace.HasValue() ? $"{businessObjectNamespace}.{innerNamespace}" : businessObjectNamespace;

            var businessObjectClassName = classConfiguration.ClassName.StripRight(_options.EntitySuffix);
            var businessObjectFilePath  = Path.Combine(businessObjectOutputDirectoryPath, $"{businessObjectClassName}.cs");

            _builder.Clear()
            .WriteLine($"using {classConfiguration.EntityNamespace};")
            .WriteUsingNamespaces()
            .WriteLine()
            .WriteNamespaceDeclaration(classNamespace: fullNamespace)
            .WriteClassDeclaration(
                className: businessObjectClassName,
                inherits: classConfiguration.InnerNamespace + "." + classConfiguration.ClassName,
                implementsInterfaces: string.Empty,
                classAttributes: "Serializable",
                applyDataAnnotationAttributes: false)
            .WriteLine("}")
            .WriteLine("}");
            string businessObjectFileText = this._builder.GetClassString();

            using (var outfile = new StreamWriter(businessObjectFilePath))
            {
                outfile.Write(value: businessObjectFileText);
            }
            _builder.Clear();
        }
Beispiel #3
0
        /// <summary>
        /// These mapping configuration methods are obsolete-ish because recent EntityFramework
        /// versions don't use MappingConfiguration classes anymore. Still, leaving in for
        /// backwards compatibility.
        /// </summary>
        /// <param name="classConfiguration"></param>
        protected void WriteEntityFrameworkMappingPartialClass(ClassConfiguration configuration)
        {
            var newClassName = BeginMappingConfigurationClass(configuration, true);

            _builder
            .WriteLine("protected void initialize()")
            .WriteLine("{")
            .WriteLine("// ADD RELATIONSHIPS AND CUSTOM LOGIC HERE")
            .WriteLine("}");
            CloseEntityConfigurationClass();
        }
Beispiel #4
0
        protected string GetBusinessObjectClassName(ClassConfiguration classConfiguration, string className)
        {
            if (_options.EntitySuffix.HasValue() &&
                className.EndsWith(_options.EntitySuffix, StringComparison.OrdinalIgnoreCase))
            {
                return(className
                       .LeftOfLast(_options.EntitySuffix));
            }

            return(className);
        }
Beispiel #5
0
        /// <summary>
        /// These mapping configuration methods are obsolete-ish because recent EntityFramework
        /// versions don't use MappingConfiguration classes anymore. Still, leaving in for
        /// backwards compatibility.
        /// </summary>
        /// <param name="classConfiguration"></param>
        protected void WriteEntityFrameworkMappingConfiguration(ClassConfiguration classConfiguration)
        {
            var newClassName = BeginMappingConfigurationClass(classConfiguration);

            _builder.WriteLine("public " + newClassName + "Mapping()")
            .WriteLine("{");     //constructor
            if (classConfiguration.PrimaryKeyColumn != null)
            {
                _builder.WriteLine("HasKey(item => item.{0});",
                                   _builder.ColumnNamePropertyNameMappings.ContainsKey(classConfiguration.PrimaryKeyColumn.ColumnName)
                        ? _builder.ColumnNamePropertyNameMappings[classConfiguration.PrimaryKeyColumn.ColumnName]
                        : classConfiguration.PrimaryKeyColumn.PropertyName);
            }
            foreach (SchemaColumnInfo schemaColumnInfo in classConfiguration.SchemaColumns)
            {
                // map any columns with different names from the corresponding entity properties:
                if (_builder.ColumnNamePropertyNameMappings.ContainsKey(schemaColumnInfo.ColumnName))
                {
                    string newPropertyName = _builder.ColumnNamePropertyNameMappings[schemaColumnInfo.ColumnName];
                    if (newPropertyName != schemaColumnInfo.ColumnName)
                    {
                        _builder.WriteLine(
                            "Property(item => item.{0}).HasColumnName(\"{1}\");", newPropertyName, schemaColumnInfo.ColumnName);
                    }
                }
            }
            if (classConfiguration.InnerNamespace != null)
            {
                if (classConfiguration.InnerNamespace.ToLower() == "dbo")
                {
                    _builder.WriteLine("ToTable(\"{0}\");", classConfiguration.UnqualifiedTableName);
                }
                else
                {
                    _builder.WriteLine("ToTable(\"{0}\", \"{1}\");", classConfiguration.UnqualifiedTableName, classConfiguration.InnerNamespace);
                }
                if (_options.GenerateCrmSpecificProperties && !newClassName.Contains("ExtensionBase"))
                {
                    _builder.WriteLine("HasRequired(item => item.Extension).WithRequiredPrincipal();");
                }
            }
            _builder.WriteLine("initialize();");
            this._builder.WriteLine("}"); //constructor
            CloseEntityConfigurationClass();
        }
Beispiel #6
0
        /// <summary>
        /// Gets the BusinessObjects output directory and ensures it exists
        /// </summary>
        /// <param name="classConfiguration"></param>
        /// <returns></returns>
        protected string GetBusinessObjectsOutputDirectory(ClassConfiguration classConfiguration = null)
        {
            var subDirectory = _options.BusinessObjectsSubdirectory ?? "";

            if (classConfiguration != null && classConfiguration.InnerNamespace.HasValue())
            {
                var innerNamespace = classConfiguration.InnerNamespace
                                     .Collapse(StringHelpers.ChangeCaseTypes.PascalCase,
                                               false,
                                               this._options.AdditionalCollapseTokens?.Split(';'));
                subDirectory = Path.Combine(subDirectory, innerNamespace);
            }
            var businessObjectsOutputDirectory = Path.Combine(_options.OutputDirectory, subDirectory).EnsureEndsWith("\\");

            if (!Directory.Exists(businessObjectsOutputDirectory))
            {
                Directory.CreateDirectory(businessObjectsOutputDirectory);
            }
            return(businessObjectsOutputDirectory);
        }
Beispiel #7
0
        /// <summary>
        /// Interrogates a table, builds the class file STRING from its output, and returns the name of the class.
        /// Note: the class's .cs file contents have still not been written after this method call.
        /// </summary>
        /// <param name="fullyQualifiedTableName"></param>
        /// <returns></returns>
        protected ClassConfiguration BuildClassForTable(string fullyQualifiedTableName, ICollection <SchemaColumnInfo> schemaColumns, string overrideEntityNamespace = null)
        {
            _builder.Clear();
            string tableName = fullyQualifiedTableName.RemoveAll(new char[] { '[', ']' });

            var    entityNamespace      = GetEntityNamespace();
            string innerNamespace       = GetInnerNamespace(tableName: tableName);
            var    fullNamespace        = innerNamespace.HasValue() ? $"{entityNamespace}.{innerNamespace}" : entityNamespace;
            string className            = GetEntityClassNameFromTableName(fullyQualifiedTableName);
            string unqualifiedTableName = StringHelpers.RightOfLast(tableName, ".");

            bool             foundPk          = false;
            SchemaColumnInfo primaryKeyColumn = null;

            if ((primaryKeyColumn = (schemaColumns.FirstOrDefault(col => col.IsKey))) != null)
            {
                foundPk = true;
            }

            var config = new ClassConfiguration(schemaColumns)
            {
                ClassName            = className,
                EntityNamespace      = entityNamespace,
                InnerNamespace       = innerNamespace,
                PrimaryKeyColumn     = primaryKeyColumn,
                UnqualifiedTableName = unqualifiedTableName
            };

            config.EntityOutputDirectory = GetEntityOutputDirectory(config);

            _builder
            .WriteUsingNamespaces()
            .WriteLine()
            .WriteNamespaceDeclaration(fullNamespace)
            .WriteClassDeclaration(
                className: className,
                // TODO: Move class-specific _Options properties onto ClassConfiguration
                inherits: _options.EntitiesInherit,
                implementsInterfaces: _options.EntitiesImplementInterfaces,
                classAttributes: _options.EntityAttributes,
                additionalFind: _options.AdditionalTokenFind,
                additionalReplace: _options.AdditionalTokenReplace,
                tableName: tableName);


            //List<SchemaColumnInfo> columnInfos = getTableColumns(fullyQualifiedTableName);
            foreach (var col in schemaColumns)
            {
                string propertyName    = col.PropertyName; //col.ColumnName;
                string propertyType    = col.DataType.Name;
                string columnName      = col.ColumnName ?? col.BaseColumnName;
                bool   useNullableType = (col.AllowDBNull && col.DataType.IsValueType);
                string newPropertyName = propertyName != col.ColumnName
                    ? propertyName
                    : col.ColumnName.Collapse(StringHelpers.ChangeCaseTypes.PascalCase, false, this._options.AdditionalCollapseTokens.Split(';'));
                if (col.IsKey || (!foundPk && (columnName.Equals(unqualifiedTableName + "ID", StringComparison.OrdinalIgnoreCase) || columnName.Equals("ID", StringComparison.OrdinalIgnoreCase))))
                {
                    foundPk          = true;
                    primaryKeyColumn = col;
                    primaryKeyColumn.PropertyName = newPropertyName = _options.PrimaryKeyGetsNamedId ? "Id" : primaryKeyColumn.PropertyName;
                    if (_options.GenerateCrmSpecificProperties && !className.EndsWith("ExtensionBase"))
                    {
                        _builder.WriteLine("public virtual {0} {1}", propertyType, newPropertyName)
                        .WriteLine("{");
                        _builder.WriteLine("get { return Id; }");
                        _builder.WriteLine("set { Id = value; }");
                        _builder.WriteLine("}");
                    }
                }

                _builder.ColumnNamePropertyNameMappings[columnName] = newPropertyName;
                AddDataAnnotationAttributes(col: col);
                _builder.WriteProperty(newPropertyName, propertyType, useNullableType, _options.UseAutomaticProperties);
            }
            if (_options.GenerateCrmSpecificProperties && !className.EndsWith("ExtensionBase"))
            {
                string extensionClassName = className.StripRight("Base") + "ExtensionBase";
                _builder.WriteProperty("Extension", extensionClassName, false, _options.UseAutomaticProperties);
            }
            _builder.WriteLine("}");
            _builder.WriteLine("}");
            return(config);
        }