Exemple #1
0
        private string ResolvePropertyName(Poco poco, PocoProperty property, string suffix)
        {
            string name = property.Name;

            if (poco.Name.Equals(property.Name))
            {
                name = name + suffix;
            }
            if (!poco.PropertyNames.Contains(name))
            {
                return(name);
            }

            int i = 0;

            if (!name.EndsWith(suffix))
            {
                name = property.Name + suffix;
            }
            var baseName = name;

            while (poco.PropertyNames.Contains(name))
            {
                i++;
                name = String.Concat(baseName, i.ToString());
            }
            return(name);
        }
Exemple #2
0
        private string AssignNavigationPropertyName(PocoGenerateStep settings, Poco poco, ForeignKey fk)
        {
            string name;

            if ((poco == fk.FkTable.Poco && fk.FkTable.Dependencies != null && fk.FkTable.Dependencies.Count(f => f.PkTable == fk.PkTable) > 1) ||
                (poco == fk.PkTable.Poco && fk.PkTable.DependenciesFrom != null && fk.PkTable.DependenciesFrom.Count(f => f.FkTable == fk.FkTable) > 1))
            {
                name = fk.Name;
            }
            else if (poco == fk.FkTable.Poco)
            {
                name = fk.PkTable.Poco.Name;
            }
            else
            {
                name = fk.FkTable.Poco.Name;
            }

            if (settings.PropertyNameForcePascalCase)
            {
                name = ToPascalCase(name);
            }
            if (name.StartsWith("fk_", StringComparison.InvariantCultureIgnoreCase))
            {
                name = name.Substring(3);
            }
            name = name.Replace("_", String.Empty);

            if (poco == fk.FkTable.Poco && name.StartsWith(poco.Table.Name, StringComparison.InvariantCultureIgnoreCase))
            {
                name = name.Substring(poco.Table.Name.Length);
            }
            return(name);
        }
Exemple #3
0
        public void ResolvePocoName(IEnumerable <Poco> allPocos, Poco poco)
        {
            int    i    = 0;
            string name = poco.Name;

            while (allPocos.Any(p => p != poco &&
                                p.Name.Equals(name, StringComparison.InvariantCulture) &&
                                p.Namespace.Equals(poco.Namespace, StringComparison.InvariantCulture)))
            {
                i++;
                name = String.Concat(poco.Name, i.ToString());
            }
            poco.Name = name;
        }
Exemple #4
0
        public IEnumerable <Poco> GeneratePocos(IEnumerable <Table> entities, PocoGenerateStep settings)
        {
            if (settings == null)
            {
                throw new Exception("Cannot generate POCOs: no settings found");
            }
            if (entities == null || !entities.Any())
            {
                throw new Exception("Cannot generate POCOs: no entities loaded");
            }

            var pocos = new List <Poco>();

            //create POCOs and resolve name conflicts
            foreach (var entity in entities.OrderBy(e => e.Name))
            {
                var poco = new Poco()
                {
                    Table          = entity,
                    Name           = entity.Name,
                    Namespace      = settings.Namespace,
                    Usings         = settings.Usings,
                    Extends        = settings.Extends,
                    AccessModifier = settings.ClassAccessModifier,
                    IsPartial      = settings.ClassPartial,
                };

                //name replace & resolve
                poco.Name = Replace(settings.ClassNameReplace, poco.Name);
                if (settings.ClassNameForcePascalCase)
                {
                    poco.Name = ToPascalCase(poco.Name);
                }
                ResolvePocoName(pocos, poco);

                Log.Debug(String.Format("POCO {0} - Assigned name: {1}", entity.Name, poco.Name));

                //properties: creation, name replace & resolve
                foreach (var column in entity.Columns.Values.OrderBy(c => c.Position))
                {
                    var property = new PocoBaseProperty()
                    {
                        Name       = column.Name,
                        Column     = column,
                        CSharpType = _sqlEngine.GetCSharpType(column, settings.PropertyNullableIfDefaultAndNotPk)
                    };
                    column.PocoProperty = property;

                    property.Name = Replace(settings.PropertyNameReplace, property.Name);
                    if (settings.PropertyNameForcePascalCase)
                    {
                        property.Name = ToPascalCase(property.Name);
                    }
                    property.Name = ResolvePropertyName(poco, property, "Property");

                    poco.BaseProperties.Add(property);
                    poco.PropertyNames.Add(property.Name);
                }
                pocos.Add(poco);
                entity.Poco = poco;
            }

            //create navigation properties
            foreach (var entity in entities)
            {
                //output dependencies
                if (entity.Dependencies != null)
                {
                    foreach (var fk in entity.Dependencies.Where(fk => fk.PkTable.Poco != null))
                    {
                        var property = new PocoNavigationProperty()
                        {
                            Name           = AssignNavigationPropertyName(settings, entity.Poco, fk),
                            IsVirtual      = settings.VirtualNavigationProperties,
                            Poco           = fk.PkTable.Poco,
                            ForeignKey     = fk,
                            BaseProperties = fk.Columns.Values.Select(c => c.FkColumn.PocoProperty)
                        };
                        property.Name = ResolvePropertyName(entity.Poco, property, "Navigation");
                        entity.Poco.OutNavigationProperties.Add(property);
                        entity.Poco.PropertyNames.Add(property.Name);
                    }
                }
                //input dependencies
                if (entity.DependenciesFrom != null)
                {
                    foreach (var fk in entity.DependenciesFrom.Where(fk => fk.FkTable.Poco != null))
                    {
                        var property = new PocoNavigationProperty()
                        {
                            Name       = AssignNavigationPropertyName(settings, entity.Poco, fk),
                            IsVirtual  = settings.VirtualNavigationProperties,
                            Poco       = fk.FkTable.Poco,
                            ForeignKey = fk
                        };

                        property.Name = ResolvePropertyName(entity.Poco, property, "Navigation");
                        entity.Poco.InNavigationProperties.Add(property);
                        entity.Poco.PropertyNames.Add(property.Name);
                    }
                }
            }
            return(pocos);
        }
Exemple #5
0
        private void WriteEntity(StringBuilder builder, ref string indent, string modelBuilderName, List <Tuple <Poco, string> > stubs, Poco poco)
        {
            if (!_sqlEngine.IsView(poco.Table) && poco.Table.Pk != null)
            {
                builder.AppendLine(String.Format("{0}{1}.Entity<{2}>(entity =>", indent, modelBuilderName, poco.Name));
            }
            else
            {
                builder.AppendLine(String.Format("{0}{1}.Query<{2}>(entity =>", indent, modelBuilderName, poco.Name));
            }

            builder.AppendLine(String.Format("{0}{{", indent));
            indent = indent.AddIndent();

            //entity name
            if (_sqlEngine.IsView(poco.Table))
            {
                builder.AppendLine(String.Format("{0}entity.ToView(\"{1}\", \"{2}\");", indent, poco.Table.Name, poco.Table.Schema));
            }
            else if (poco.Table.Pk != null)
            {
                builder.AppendLine(String.Format("{0}entity.ToTable(\"{1}\", \"{2}\");", indent, poco.Table.Name, poco.Table.Schema));
            }
            else
            {
                //mandatory pre-stub
                string stub = String.Concat(poco.Name, "Query");
                stubs.Add(new Tuple <Poco, string>(poco, stub));
                builder.AppendLine(String.Format("{0}{1}(entity);", indent, stub));
            }

            //pk
            if (poco.Table.Pk != null && poco.Table.Pk.Columns.Any())
            {
                if (poco.Table.Pk.Columns.Count == 1)
                {
                    builder.AppendLine(String.Format("{0}entity.HasKey(e => e.{1});", indent, poco.Table.Pk.Columns.Values.First().ColumnName));
                }
                else
                {
                    builder.AppendLine(String.Format("{0}entity.HasKey(e => new {{ {1} }});",
                                                     indent,
                                                     String.Join(", ", poco.Table.Pk.Columns.Values.OrderBy(c => c.Position).Select(c => String.Concat("e.", c.ColumnName)))));
                }
            }

            //indices
            if (_settings.IncludeIndices && poco.Table.Pk != null && poco.Table.Indices != null && poco.Table.Indices.Any(idx => !idx.IsPrimaryKey))
            {
                foreach (var index in poco.Table.Indices.Where(idx => !idx.IsPrimaryKey))
                {
                    if (!index.Columns.Any())
                    {
                        continue;
                    }
                    if (index.Columns.Count() == 1)
                    {
                        builder.AppendLine(String.Format("{0}entity.HasIndex(e => e.{1});", indent, index.Columns.Values.First().Column.PocoProperty.Name));
                    }
                    else
                    {
                        builder.AppendLine(String.Format("{0}entity.HasIndex({1});",
                                                         indent,
                                                         String.Join(", ", index.Columns.Values.OrderBy(c => c.Position).Select(c => String.Concat("\"", c.Column.PocoProperty.Name, "\"")))));
                    }
                }
            }

            //columns
            foreach (var property in poco.BaseProperties)
            {
                var directives = new List <string>();

                if (property.Column.Dependencies != null && property.Column.Dependencies.Any())
                {
                    directives.Add(".ValueGeneratedNever()");
                }

                if (!String.Equals(property.Name, property.Column.Name, StringComparison.InvariantCulture))
                {
                    directives.Add(String.Format(".HasColumnName(@\"{0}\")", property.Column.Name));
                }

                if (property.Column.DataType.Equals("date", StringComparison.InvariantCultureIgnoreCase) ||
                    property.Column.DataType.Equals("datetime", StringComparison.InvariantCultureIgnoreCase) ||
                    property.Column.DataType.Equals("money", StringComparison.InvariantCultureIgnoreCase) ||
                    property.Column.DataType.Equals("time", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (property.Column.DateTimePrecision != null)
                    {
                        directives.Add(String.Format(".HasColumnType(\"{0}({1})\")", property.Column.DataType, property.Column.DateTimePrecision));
                    }
                    else
                    {
                        directives.Add(String.Format(".HasColumnType(\"{0}\")", property.Column.DataType));
                    }
                }

                if (_sqlEngine.IsString(property.Column))
                {
                    if (property.Column.CharacterMaximumLength >= 0)
                    {
                        directives.Add(String.Format(".HasMaxLength({0})", property.Column.CharacterMaximumLength));
                    }
                    directives.Add(String.Format(".IsUnicode({0})", _sqlEngine.IsUnicode(property.Column) ? "true" : "false"));
                }

                if (!property.Column.IsNullable && (poco.Table.Pk == null || !poco.Table.Pk.Columns.Values.Any(c => c.ColumnName.Equals(property.Column.Name))))
                {
                    directives.Add(".IsRequired()");
                }

                if (!String.IsNullOrWhiteSpace(property.Column.Default))
                {
                    directives.Add(String.Format(".HasDefaultValueSql(\"{0}\")", property.Column.Default));
                }

                if (property.Column.IsIdentity)
                {
                    var directive = _sqlEngine.GetIdentitySpecifier(property.Column);
                    if (!String.IsNullOrWhiteSpace(directive))
                    {
                        directives.Add(directive);
                    }
                }

                if (directives.Any())
                {
                    builder.AppendLine();
                    builder.Append(String.Format("{0}entity.Property(e => e.{1})", indent, property.Name));
                    if (directives.Count == 1)
                    {
                        builder.AppendLine(String.Concat(directives.First(), ";"));
                    }
                    else
                    {
                        indent = indent.AddIndent();
                        foreach (var directive in directives)
                        {
                            builder.AppendLine();
                            builder.Append(String.Format("{0}{1}", indent, directive));
                        }
                        builder.AppendLine(";");
                        indent = indent.RemoveIndent();
                    }
                }
            }

            //fk
            foreach (var property in poco.OutNavigationProperties)
            {
                var externalNavigationProperty = property.Poco.InNavigationProperties.FirstOrDefault(n => n.ForeignKey == property.ForeignKey);
                if (externalNavigationProperty != null)
                {
                    builder.AppendLine();
                    builder.AppendLine(String.Format("{0}entity.HasOne(f => f.{1})", indent, property.Name));
                    indent = indent.AddIndent();

                    if (property.ForeignKey.IsOne())
                    {
                        builder.AppendLine(String.Format("{0}.WithOne(p => p.{1})", indent, externalNavigationProperty.Name));
                    }
                    else
                    {
                        builder.AppendLine(String.Format("{0}.WithMany(p => p.{1})", indent, externalNavigationProperty.Name));
                    }

                    if (property.BaseProperties != null && property.BaseProperties.Any())
                    {
                        if (property.ForeignKey.IsOne())
                        {
                            builder.AppendLine(String.Format("{0}.HasForeignKey<{1}>({2})", indent,
                                                             poco.Name,
                                                             String.Join(", ", property.BaseProperties.Select(p => String.Concat("\"", p.Name, "\"")))));
                        }
                        else
                        {
                            builder.AppendLine(String.Format("{0}.HasForeignKey({1})", indent,
                                                             String.Join(", ", property.BaseProperties.Select(p => String.Concat("\"", p.Name, "\"")))));
                        }
                    }

                    var onDelete = _sqlEngine.ForeignKeyRuleString(property.ForeignKey.DeleteRuleStr);
                    if (onDelete != null)
                    {
                        builder.AppendLine(String.Format("{0}.OnDelete({1})", indent, onDelete));
                    }

                    builder.AppendLine(String.Format("{0}.HasConstraintName(\"{1}\");", indent, property.ForeignKey.Name));

                    indent = indent.RemoveIndent();
                }
            }

            //optional stub
            if (_settings.IncludeOptionalStubs)
            {
                string stub = String.Concat(poco.Name, "Init");
                stubs.Add(new Tuple <Poco, string>(poco, stub));
                builder.AppendLine(String.Format("{0}{1}(entity);", indent, stub));
            }

            indent = indent.RemoveIndent();
            builder.AppendLine(String.Format("{0}}});", indent));
            builder.AppendLine();
        }