Пример #1
0
        /// <summary>
        /// Generate entity type navigation properties.
        /// </summary>
        /// <param name="entityType">Represents an entity type in an <see cref="T:Microsoft.EntityFrameworkCore.Metadata.IModel" />.</param>
        protected override void GenerateNavigationProperties(IEntityType entityType)
        {
            Check.NotNull(entityType, nameof(entityType));

            var sortedNavigations = entityType.GetScaffoldNavigations(_options.Value)
                                    .OrderBy(n => n.IsDependentToPrincipal() ? 0 : 1)
                                    .ThenBy(n => n.IsCollection() ? 1 : 0);

            if (sortedNavigations.Any())
            {
                var navProperties = new List <Dictionary <string, object> >();

                foreach (var navigation in sortedNavigations)
                {
                    NavPropertyAnnotations = new List <Dictionary <string, object> >();

                    if (UseDataAnnotations)
                    {
                        GenerateNavigationDataAnnotations(navigation);
                    }

                    navProperties.Add(new Dictionary <string, object>
                    {
                        { "nav-property-collection", navigation.IsCollection() },
                        { "nav-property-type", navigation.GetTargetType().Name },
                        { "nav-property-name", navigation.Name },
                        { "nav-property-annotations", NavPropertyAnnotations },
                    });
                }

                var transformedNavProperties = EntityTypeTransformationService.TransformNavigationProperties(navProperties);

                TemplateData.Add("nav-properties", transformedNavProperties);
            }
        }
Пример #2
0
        /// <summary>
        /// Generate entity type properties.
        /// </summary>
        /// <param name="entityType">Represents an entity type in an <see cref="T:Microsoft.EntityFrameworkCore.Metadata.IModel" />.</param>
        protected override void GenerateProperties(IEntityType entityType)
        {
            Check.NotNull(entityType, nameof(entityType));

            var properties = new List <Dictionary <string, object> >();

            foreach (var property in entityType.GetProperties().OrderBy(p => p.GetColumnOrdinal()))
            {
                PropertyAnnotationsData = new List <Dictionary <string, object> >();

                if (UseDataAnnotations)
                {
                    GeneratePropertyDataAnnotations(property);
                }

                properties.Add(new Dictionary <string, object>
                {
                    { "property-type", CSharpHelper.Reference(property.ClrType) },
                    { "property-name", property.Name },
                    { "property-annotations", PropertyAnnotationsData }
                });
            }

            var transformedProperties = EntityTypeTransformationService.TransformProperties(properties);

            TemplateData.Add("properties", transformedProperties);
        }
Пример #3
0
        /// <summary>
        /// Generate entity type navigation properties.
        /// </summary>
        /// <param name="entityType">Represents an entity type in an <see cref="T:Microsoft.EntityFrameworkCore.Metadata.IModel" />.</param>
        protected override void GenerateNavigationProperties(IEntityType entityType)
        {
            Check.NotNull(entityType, nameof(entityType));

            var sortedNavigations = entityType.GetNavigations()
                                    .OrderBy(n => n.IsOnDependent ? 0 : 1)
                                    .ThenBy(n => n.IsCollection ? 1 : 0);

            if (sortedNavigations.Any())
            {
                var navProperties = new List <Dictionary <string, object> >();

                foreach (var navigation in sortedNavigations)
                {
                    // TODO: Resolve TransformNavPropertyName() method
                    NavEntityPropertyInfo navEntityPropertyInfo = ResolvingNamesService.ResolvingName(navigation);
                    navProperties.Add(new Dictionary <string, object>
                    {
                        { "foregin-entity-name", navEntityPropertyInfo.ForeginEntityName },
                        { "field-name", navEntityPropertyInfo.FieldName },
                        { "nav-property-collection", navigation.IsCollection },
                        { "nav-property-type", navigation.TargetEntityType.Name },
                        { "nav-property-name", TypeScriptHelper.ToCamelCase(navigation.Name) },
                        { "nav-property-annotations", new List <Dictionary <string, object> >() },
                        { "nullable-reference-types", _options?.Value?.EnableNullableReferenceTypes == true }
                    });
                }

                var transformedNavProperties = EntityTypeTransformationService.TransformNavigationProperties(entityType.Name, navProperties);

                TemplateData.Add("nav-properties", transformedNavProperties);
            }
        }
        /// <summary>
        /// Generate entity type navigation properties.
        /// </summary>
        /// <param name="entityType">Represents an entity type in an <see cref="T:Microsoft.EntityFrameworkCore.Metadata.IModel" />.</param>
        protected virtual void GenerateNavigationProperties(IEntityType entityType)
        {
            if (entityType == null)
            {
                throw new ArgumentNullException(nameof(entityType));
            }

            var sortedNavigations = entityType.GetNavigations()
                                    .OrderBy(n => n.IsDependentToPrincipal() ? 0 : 1)
                                    .ThenBy(n => n.IsCollection() ? 1 : 0);

            if (sortedNavigations.Any())
            {
                var navProperties = new List <Dictionary <string, object> >();

                foreach (var navigation in sortedNavigations)
                {
                    navProperties.Add(new Dictionary <string, object>
                    {
                        { "nav-property-collection", navigation.IsCollection() },
                        { "nav-property-type", navigation.GetTargetType().Name },
                        { "nav-property-name", TypeScriptHelper.ToCamelCase(navigation.Name) },
                        { "nav-property-annotations", new List <Dictionary <string, object> >() },
                    });
                }

                var transformedNavProperties = EntityTypeTransformationService.TransformNavigationProperties(navProperties);

                TemplateData.Add("nav-properties", transformedNavProperties);
            }
        }
        /// <summary>
        /// Generate entity type constructor.
        /// </summary>
        /// <param name="entityType">Represents an entity type in an <see cref="T:Microsoft.EntityFrameworkCore.Metadata.IModel" />.</param>
        protected override void GenerateConstructor(IEntityType entityType)
        {
            Check.NotNull(entityType, nameof(entityType));

            var collectionNavigations = entityType.GetScaffoldNavigations(_options.Value)
                                        .Where(n => n.IsCollection()).ToList();

            if (collectionNavigations.Count > 0)
            {
                var lines = new List <Dictionary <string, object> >();

                foreach (var navigation in collectionNavigations)
                {
                    lines.Add(new Dictionary <string, object>
                    {
                        { "property-name", navigation.Name },
                        { "property-type", navigation.GetTargetType().Name }
                    });
                }

                var transformedLines = EntityTypeTransformationService.TransformConstructor(lines);

                TemplateData.Add("lines", transformedLines);
            }
        }
        /// <summary>
        /// Generate OnModelBuilding method.
        /// </summary>
        /// <param name="model">Metadata about the shape of entities, the relationships between them, and how they map to the database.</param>
        /// <param name="useDataAnnotations">Use fluent modeling API if false.</param>
        protected virtual void GenerateConfiguration(IEntityType entityType, bool useDataAnnotations)
        {
            if (entityType == null)
            {
                throw new ArgumentNullException(nameof(entityType));
            }

            var transformedEntityName = EntityTypeTransformationService.TransformEntityName(entityType.DisplayName());
            var sb = new IndentedStringBuilder();

            using (sb.Indent())
            {
                sb.IncrementIndent();
                sb.AppendLine($"public void Configure(EntityTypeBuilder<{transformedEntityName}> builder)");
                sb.Append("{");

                using (sb.Indent())
                {
                    GenerateEntityType(entityType, useDataAnnotations, sb);

                    //GenerateSequence(sequence, sb);

                    sb.AppendLine();
                }

                sb.Append("}");

                var configuration = sb.ToString();
                TemplateData.Add("configuration", configuration);
            }
        }
        /// <summary>
        /// Generate entity type properties.
        /// </summary>
        /// <param name="entityType">Represents an entity type in an <see cref="T:Microsoft.EntityFrameworkCore.Metadata.IModel" />.</param>
        protected virtual void GenerateProperties(IEntityType entityType)
        {
            if (entityType == null)
            {
                throw new ArgumentNullException(nameof(entityType));
            }

            var properties = new List <Dictionary <string, object> >();

            foreach (var property in entityType.GetProperties().OrderBy(p => p.Scaffolding().ColumnOrdinal))
            {
                PropertyAnnotationsData = new List <Dictionary <string, object> >();

                if (UseDataAnnotations)
                {
                    GeneratePropertyDataAnnotations(property);
                }

                properties.Add(new Dictionary <string, object>
                {
                    { "property-type", CSharpHelper.Reference(property.ClrType) },
                    { "property-name", property.Name },
                    { "property-annotations", PropertyAnnotationsData }
                });
            }

            var transformedProperties = EntityTypeTransformationService.TransformProperties(properties);

            TemplateData.Add("properties", transformedProperties);
        }
Пример #8
0
        /// <summary>
        /// Generate the DbContext class.
        /// </summary>
        /// <param name="model">Metadata about the shape of entities, the relationships between them, and how they map to the database.</param>
        /// <param name="contextName">Name of DbContext class.</param>
        /// <param name="connectionString">Database connection string.</param>
        /// <param name="useDataAnnotations">Use fluent modeling API if false.</param>
        /// <param name="suppressConnectionStringWarning">Suppress connection string warning.</param>
        protected virtual void GenerateClass(
            IModel model,
            string contextName,
            string connectionString,
            bool useDataAnnotations,
            bool suppressConnectionStringWarning)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            if (contextName == null)
            {
                throw new ArgumentNullException(nameof(contextName));
            }
            if (connectionString == null)
            {
                throw new ArgumentNullException(nameof(connectionString));
            }

            TemplateData.Add("class", contextName);

            GenerateDbSets(model);
            GenerateEntityTypeErrors(model);
            GenerateOnConfiguring(connectionString, suppressConnectionStringWarning);
            GenerateOnModelCreating(model, useDataAnnotations);
        }
        /// <summary>
        /// Generate entity type data annotations.
        /// </summary>
        /// <param name="entityType">Represents an entity type in an <see cref="T:Microsoft.EntityFrameworkCore.Metadata.IModel" />.</param>
        protected override void GenerateEntityTypeDataAnnotations(IEntityType entityType)
        {
            Check.NotNull(entityType, nameof(entityType));

            //GenerateTableAttribute(entityType);

            ClassAnnotationsData = new List <Dictionary <string, object> >();

            GenerateKeylessAttribute(entityType);
            GenerateTableAttribute(entityType);
            GenerateIndexAttributes(entityType);

            var annotations = AnnotationCodeGenerator
                              .FilterIgnoredAnnotations(entityType.GetAnnotations())
                              .ToDictionary(a => a.Name, a => a);

            AnnotationCodeGenerator.RemoveAnnotationsHandledByConventions(entityType, annotations);

            foreach (var attribute in AnnotationCodeGenerator.GenerateDataAnnotationAttributes(entityType, annotations))
            {
                var attributeWriter = new AttributeWriter(attribute.Type.Name);
                foreach (var argument in attribute.Arguments)
                {
                    attributeWriter.AddParameter(CSharpHelper.UnknownLiteral(argument));
                }
            }

            TemplateData.Add("class-annotations", ClassAnnotationsData);
        }
        /// <summary>
        /// Generate entity type constructor.
        /// </summary>
        /// <param name="entityType">Represents an entity type in an <see cref="T:Microsoft.EntityFrameworkCore.Metadata.IModel" />.</param>
        protected virtual void GenerateConstructor(IEntityType entityType)
        {
            if (entityType == null)
            {
                throw new ArgumentNullException(nameof(entityType));
            }

            var collectionNavigations = entityType.GetNavigations().Where(n => n.IsCollection()).ToList();

            if (collectionNavigations.Count > 0)
            {
                var lines = new List <Dictionary <string, object> >();

                foreach (var navigation in collectionNavigations)
                {
                    lines.Add(new Dictionary <string, object>
                    {
                        { "property-name", navigation.Name },
                        { "property-type", navigation.GetTargetType().Name },
                    });
                }

                var transformedLines = EntityTypeTransformationService.TransformConstructor(lines);

                TemplateData.Add("lines", transformedLines);
            }
        }
Пример #11
0
        /// <summary>
        /// Generate entity type navigation properties.
        /// </summary>
        /// <param name="entityType">Represents an entity type in an <see cref="T:Microsoft.EntityFrameworkCore.Metadata.IModel" />.</param>
        protected override void GenerateNavigationProperties(IEntityType entityType)
        {
            Check.NotNull(entityType, nameof(entityType));

            var sortedNavigations = entityType.GetNavigations()
                                    .OrderBy(n => n.IsDependentToPrincipal() ? 0 : 1)
                                    .ThenBy(n => n.IsCollection() ? 1 : 0);

            if (sortedNavigations.Any())
            {
                var navProperties = new List <Dictionary <string, object> >();

                foreach (var navigation in sortedNavigations)
                {
                    navProperties.Add(new Dictionary <string, object>
                    {
                        { "nav-property-collection", navigation.IsCollection() },
                        { "nav-property-type", navigation.GetTargetType().Name },
                        { "nav-property-name", TypeScriptHelper.ToCamelCase(navigation.Name) },
                        { "nav-property-annotations", new List <Dictionary <string, object> >() },
                        { "nullable-reference-types", _options?.Value?.EnableNullableReferenceTypes == true }
                    });
                }

                var transformedNavProperties = EntityTypeTransformationService.TransformNavigationProperties(navProperties);

                TemplateData.Add("nav-properties", transformedNavProperties);
            }
        }
Пример #12
0
        /// <summary>
        /// Generate OnConfiguring method.
        /// </summary>
        /// <param name="connectionString">Database connection string.</param>
        /// <param name="suppressConnectionStringWarning">Suppress connection string warning.</param>
        protected virtual void GenerateOnConfiguring(
            string connectionString,
            bool suppressConnectionStringWarning)
        {
            if (connectionString == null)
            {
                throw new ArgumentNullException(nameof(connectionString));
            }

            var sb = new IndentedStringBuilder();

            using (sb.Indent())
            {
                sb.IncrementIndent();
                sb.AppendLine("protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)");
                sb.AppendLine("{");

                using (sb.Indent())
                {
                    sb.AppendLine("if (!optionsBuilder.IsConfigured)");
                    sb.AppendLine("{");

                    if (HandlebarsScaffoldingOptions.IncludeConnectionString)
                    {
                        using (sb.Indent())
                        {
                            if (!suppressConnectionStringWarning)
                            {
                                sb.DecrementIndent()
                                .DecrementIndent()
                                .DecrementIndent()
                                .DecrementIndent()
                                .AppendLine("#warning " + DesignStrings.SensitiveInformationWarning)
                                .IncrementIndent()
                                .IncrementIndent()
                                .IncrementIndent()
                                .IncrementIndent();
                            }

                            sb.Append("optionsBuilder")
                            .Append(
                                ProviderConfigurationCodeGenerator != null
                                        ? CSharpHelper.Fragment(
                                    ProviderConfigurationCodeGenerator.GenerateUseProvider(connectionString, null))
#pragma warning disable CS0618 // Type or member is obsolete
                                    : LegacyProviderCodeGenerator.GenerateUseProvider(connectionString, Language))
#pragma warning restore CS0618 // Type or member is obsolete
                            .AppendLine(";");
                        }
                    }

                    sb.AppendLine("}");
                }
                sb.AppendLine("}");

                var onConfiguring = sb.ToString();
                TemplateData.Add("on-configuring", onConfiguring);
            }
        }
        /// <summary>
        /// Generate entity type navigation properties.
        /// </summary>
        /// <param name="entityType">Represents an entity type in an <see cref="T:Microsoft.EntityFrameworkCore.Metadata.IModel" />.</param>
        protected override void GenerateNavigationProperties(IEntityType entityType)
        {
            Check.NotNull(entityType, nameof(entityType));

            var sortedNavigations = entityType.GetScaffoldNavigations(_options.Value)
                                    .OrderBy(n => n.IsOnDependent ? 0 : 1)
                                    .ThenBy(n => n.IsCollection ? 1 : 0);

            if (sortedNavigations.Any())
            {
                var navProperties = new List <Dictionary <string, object> >();



                foreach (var navigation in sortedNavigations)
                {
                    NavPropertyAnnotations = new List <Dictionary <string, object> >();

                    // TODO: Resolve TransformNavPropertyName() method
                    NavEntityPropertyInfo navEntityPropertyInfo = ResolvingNamesService.ResolvingName(navigation);

                    if (UseDataAnnotations)
                    {
                        GenerateNavigationDataAnnotations(navigation);
                    }

                    var propertyIsNullable = !navigation.IsCollection && (
                        navigation.IsOnDependent
                        ? !navigation.ForeignKey.IsRequired
                        : !navigation.ForeignKey.IsRequiredDependent
                        );
                    var navPropertyType = navigation.TargetEntityType.Name;
                    if (_options?.Value?.EnableNullableReferenceTypes == true &&
                        !navPropertyType.EndsWith("?") &&
                        propertyIsNullable)
                    {
                        navPropertyType += "?";
                    }

                    navProperties.Add(new Dictionary <string, object>
                    {
                        { "foregin-entity-name", navEntityPropertyInfo.ForeginEntityName },
                        { "field-name", navEntityPropertyInfo.FieldName },
                        { "nav-property-collection", navigation.IsCollection },
                        { "nav-property-type", navPropertyType },
                        { "nav-property-name", navigation.Name },
                        { "nav-property-annotations", NavPropertyAnnotations },
                        { "nav-property-isnullable", propertyIsNullable },
                        { "nullable-reference-types", _options?.Value?.EnableNullableReferenceTypes == true }
                    });
                }

                var transformedNavProperties = EntityTypeTransformationService.TransformNavigationProperties(entityType.Name, navProperties);

                TemplateData.Add("nav-properties", transformedNavProperties);
            }
        }
Пример #14
0
        /// <summary>
        /// Generate entity type class.
        /// </summary>
        /// <param name="entityType">Represents an entity type in an <see cref="T:Microsoft.EntityFrameworkCore.Metadata.IModel" />.</param>
        protected override void GenerateClass(IEntityType entityType)
        {
            Check.NotNull(entityType, nameof(entityType));

            var transformedEntityName = EntityTypeTransformationService.TransformEntityName(entityType.Name);

            TemplateData.Add("class", transformedEntityName);

            GenerateConstructor(entityType);
            GenerateProperties(entityType);
            GenerateNavigationProperties(entityType);
        }
Пример #15
0
 public static string SendLogintemplate(string accesstoken, string name)
 {
     if (accesstoken != null && name != null)
     {
         var searchmodel = new Template();
         var data        = new TemplateData();
         searchmodel.touser      = "******";
         searchmodel.template_id = "MkAXA32hZhVDk_lb2TNtvBNR1jqh58ZlG2aB-nBaM-Y";
         searchmodel.url         = "111.230.151.235/New";
         data.Add("first", new Item("用户登录管理面板", "#000000"));
         data.Add("keyword1", new Item(GetLocalIP(), "#FF4040"));
         data.Add("keyword2", new Item(name, "#FF4040"));
         data.Add("keyword3", new Item(DateTime.Now.ToString(), "#FF4040"));
         data.Add("remark", new Item("请留意!!", "#000000"));
         searchmodel.data = data;
         var str     = JsonConvert.SerializeObject(searchmodel);
         var urlstr  = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accesstoken;
         var jsonstr = Httpgetpost.Post(urlstr, str);
         return(jsonstr);
     }
     return(null);
 }
Пример #16
0
 public static string SendSearchtemplate(string accesstoken, string content)
 {
     if (accesstoken != null && content != null)
     {
         var searchmodel = new Template();
         var data        = new TemplateData();
         searchmodel.touser      = "******";
         searchmodel.template_id = "rNptNzNkbzunBF3zsukNfBC-DAwrUv8gnmjrcrrGKc4";
         searchmodel.url         = "111.230.151.235/New";
         data.Add("first", new Item("使用了搜索功能", "#000000"));
         data.Add("keyword1", new Item(GetLocalIP(), "#FF4040"));
         data.Add("keyword2", new Item(content, "#FF4040"));
         data.Add("keyword3", new Item(DateTime.Now.ToString(), "#FF4040"));
         data.Add("remark", new Item("请留意!!", "#000000"));
         searchmodel.data = data;
         var str     = JsonConvert.SerializeObject(searchmodel);
         var urlstr  = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accesstoken;
         var jsonstr = Httpgetpost.Post(urlstr, str);
         return(jsonstr);
     }
     return(null);
 }
Пример #17
0
        private void GenerateEntityTypeErrors(IModel model)
        {
            var entityTypeErrors = new List <Dictionary <string, object> >();

            foreach (var entityTypeError in model.Scaffolding().EntityTypeErrors)
            {
                entityTypeErrors.Add(new Dictionary <string, object>
                {
                    { "entity-type-error", $"// {entityTypeError.Value} Please see the warning messages." },
                });
            }

            TemplateData.Add("entity-type-errors", entityTypeErrors);
        }
        /// <summary>
        /// Generate entity type class.
        /// </summary>
        /// <param name="entityType">Represents an entity type in an <see cref="T:Microsoft.EntityFrameworkCore.Metadata.IModel" />.</param>
        protected virtual void GenerateClassAndMap(IEntityType entityType, bool useDataAnnotations)
        {
            if (entityType == null)
            {
                throw new ArgumentNullException(nameof(entityType));
            }

            var transformedEntityName = EntityTypeTransformationService.TransformEntityName(entityType.Name);

            TemplateData.Add("class", transformedEntityName);
            TemplateData.Add("class-map", transformedEntityName + "Map");

            GenerateConfiguration(entityType, useDataAnnotations);
        }
        /// <summary>
        /// Generate entity type class.
        /// </summary>
        /// <param name="entityType">Represents an entity type in an <see cref="T:Microsoft.EntityFrameworkCore.Metadata.IModel" />.</param>
        protected virtual void GenerateClass(IEntityType entityType)
        {
            if (entityType == null)
            {
                throw new ArgumentNullException(nameof(entityType));
            }

            var transformedEntityName = EntityTypeTransformationService.TransformEntityName(entityType.Name);

            TemplateData.Add("class", transformedEntityName);

            GenerateConstructor(entityType);
            GenerateProperties(entityType);
            GenerateNavigationProperties(entityType);
        }
Пример #20
0
        private void GenerateDbSets(IModel model)
        {
            var dbSets = new List <Dictionary <string, object> >();

            foreach (var entityType in model.GetEntityTypes())
            {
                var transformedEntityName = EntityTypeTransformationService.TransformEntityName(entityType.Name);
                dbSets.Add(new Dictionary <string, object>
                {
                    { "set-property-type", transformedEntityName },
                    { "set-property-name", entityType.Scaffolding().DbSetName },
                });
            }

            TemplateData.Add("dbsets", dbSets);
        }
        protected override void GenerateProperties(IEntityType entityType)
        {
            var properties = new List <Dictionary <string, object> >();

#pragma warning disable EF1001 // Internal EF Core API usage.
            foreach (var property in entityType.GetProperties().OrderBy(p => p.GetColumnOrdinal()))
#pragma warning restore EF1001 // Internal EF Core API usage.
            {
                PropertyAnnotationsData = new List <Dictionary <string, object> >();

                if (UseDataAnnotations)
                {
                    GeneratePropertyDataAnnotations(property);
                }

                var propertyType = CSharpHelper.Reference(property.ClrType);
                if (_options?.Value?.EnableNullableReferenceTypes == true &&
                    property.IsNullable &&
                    !propertyType.EndsWith("?"))
                {
                    propertyType += "?";
                }
                properties.Add(new Dictionary <string, object>
                {
                    { "property-type", propertyType },
                    { "property-name", property.Name },
                    { "property-annotations", PropertyAnnotationsData },
                    { "property-comment", property.GetComment() },
                    { "property-isnullable", property.IsNullable },
                    { "nullable-reference-types", _options?.Value?.EnableNullableReferenceTypes == true },

                    // Add new item to template data
                    { "property-isprimarykey", property.IsPrimaryKey() }
                });
            }

            var transformedProperties = EntityTypeTransformationService.TransformProperties(properties);

            // Add to transformed properties
            for (int i = 0; i < transformedProperties.Count; i++)
            {
                transformedProperties[i].Add("property-isprimarykey", properties[i]["property-isprimarykey"]);
            }

            TemplateData.Add("properties", transformedProperties);
        }
Пример #22
0
        /// <summary>
        /// Generate entity type class.
        /// </summary>
        /// <param name="entityType">Represents an entity type in an <see cref="T:Microsoft.EntityFrameworkCore.Metadata.IModel" />.</param>
        protected override void GenerateClass(IEntityType entityType)
        {
            Check.NotNull(entityType, nameof(entityType));

            if (UseDataAnnotations)
            {
                GenerateEntityTypeDataAnnotations(entityType);
            }

            var transformedEntityName = EntityTypeTransformationService.TransformTypeEntityName(entityType.Name);

            TemplateData.Add("comment", entityType.GetComment());
            TemplateData.Add("class", transformedEntityName);

            GenerateConstructor(entityType);
            GenerateProperties(entityType);
            GenerateNavigationProperties(entityType);
        }
        /// <summary>
        /// Generate entity type imports.
        /// </summary>
        /// <param name="entityType">Represents an entity type in an <see cref="T:Microsoft.EntityFrameworkCore.Metadata.IModel" />.</param>
        protected virtual void GenerateImports(IEntityType entityType)
        {
            Check.NotNull(entityType, nameof(entityType));

            var imports = new List <Dictionary <string, object> >();

            foreach (var ns in entityType.GetProperties()
                     .SelectMany(p => p.ClrType.GetNamespaces())
                     .Where(ns => ns != "System" && ns != "System.Collections.Generic")
                     .Distinct())
            {
                imports.Add(new Dictionary <string, object> {
                    { "import", ns }
                });
            }

            TemplateData.Add("imports", imports);
        }
Пример #24
0
        /// <summary>
        /// Generate entity type properties.
        /// </summary>
        /// <param name="entityType">Represents an entity type in an <see cref="T:Microsoft.EntityFrameworkCore.Metadata.IModel" />.</param>
        protected override void GenerateProperties(IEntityType entityType)
        {
            Check.NotNull(entityType, nameof(entityType));

            var properties = new List <Dictionary <string, object> >();

            foreach (var property in entityType.GetProperties().OrderBy(p => p.GetColumnOrdinal()))
            {
                properties.Add(new Dictionary <string, object>
                {
                    { "property-type", TypeScriptHelper.TypeName(property.ClrType) },
                    { "property-name", TypeScriptHelper.ToCamelCase(property.Name) },
                    { "property-annotations", new List <Dictionary <string, object> >() },
                });
            }

            var transformedProperties = EntityTypeTransformationService.TransformProperties(properties);

            TemplateData.Add("properties", transformedProperties);
        }
Пример #25
0
        /// <summary>
        /// Generate entity type imports.
        /// </summary>
        /// <param name="entityType">Represents an entity type in an <see cref="T:Microsoft.EntityFrameworkCore.Metadata.IModel" />.</param>
        protected virtual void GenerateImports(IEntityType entityType)
        {
            Check.NotNull(entityType, nameof(entityType));

            var sortedNavigations = entityType.GetNavigations()
                                    .OrderBy(n => n.IsDependentToPrincipal() ? 0 : 1)
                                    .ThenBy(n => n.IsCollection() ? 1 : 0)
                                    .Distinct();

            if (sortedNavigations.Any())
            {
                var imports = new List <Dictionary <string, object> >();
                foreach (var navigation in sortedNavigations)
                {
                    imports.Add(new Dictionary <string, object> {
                        { "import", navigation.GetTargetType().Name }
                    });
                }
                TemplateData.Add("imports", imports);
            }
        }
        /// <summary>
        /// Generate entity type properties.
        /// </summary>
        /// <param name="entityType">Represents an entity type in an <see cref="T:Microsoft.EntityFrameworkCore.Metadata.IModel" />.</param>
        protected virtual void GenerateProperties(IEntityType entityType)
        {
            if (entityType == null)
            {
                throw new ArgumentNullException(nameof(entityType));
            }

            var properties = new List <Dictionary <string, object> >();

            foreach (var property in entityType.GetProperties().OrderBy(p => p.Scaffolding().ColumnOrdinal))
            {
                properties.Add(new Dictionary <string, object>
                {
                    { "property-type", TypeScriptHelper.TypeName(property.ClrType) },
                    { "property-name", TypeScriptHelper.ToCamelCase(property.Name) },
                    { "property-annotations", new List <Dictionary <string, object> >() },
                });
            }

            var transformedProperties = EntityTypeTransformationService.TransformProperties(properties);

            TemplateData.Add("properties", transformedProperties);
        }
Пример #27
0
        /// <summary>
        /// Generate entity type properties.
        /// </summary>
        /// <param name="entityType">Represents an entity type in an <see cref="T:Microsoft.EntityFrameworkCore.Metadata.IModel" />.</param>
        protected override void GenerateProperties(IEntityType entityType)
        {
            Check.NotNull(entityType, nameof(entityType));

            var properties = new List <Dictionary <string, object> >();

            foreach (var property in entityType.GetProperties().OrderBy(p => p.GetColumnOrdinal()))
            {
                properties.Add(new Dictionary <string, object>
                {
                    { "property-type", TypeScriptHelper.TypeName(property.ClrType) },
                    { "property-name", TypeScriptHelper.ToCamelCase(property.Name) },
                    { "property-annotations", new List <Dictionary <string, object> >() },
                    { "property-comment", property.GetComment() },
                    { "property-isnullable", property.IsNullable },
                    { "nullable-reference-types", _options?.Value?.EnableNullableReferenceTypes == true }
                });
            }

            var transformedProperties = EntityTypeTransformationService.TransformProperties(properties);

            TemplateData.Add("properties", transformedProperties);
        }
        private void GenerateTableAttribute(IEntityType entityType)
        {
            var tableName     = entityType.GetTableName();
            var schema        = entityType.GetSchema();
            var defaultSchema = entityType.Model.GetDefaultSchema();

            var schemaParameterNeeded = schema != null && schema != defaultSchema;
            var tableAttributeNeeded  = schemaParameterNeeded || tableName != null && tableName != entityType.GetDbSetName();

            if (tableAttributeNeeded)
            {
                var tableAttribute = new AttributeWriter(nameof(TableAttribute));

                tableAttribute.AddParameter(CSharpHelper.Literal(tableName));

                if (schemaParameterNeeded)
                {
                    tableAttribute.AddParameter($"{nameof(TableAttribute.Schema)} = {CSharpHelper.Literal(schema)}");
                }

                TemplateData.Add("class-annotation", tableAttribute.ToString());
            }
        }
        /// <summary>
        /// Generate entity type properties.
        /// </summary>
        /// <param name="entityType">Represents an entity type in an <see cref="T:Microsoft.EntityFrameworkCore.Metadata.IModel" />.</param>
        protected override void GenerateProperties(IEntityType entityType)
        {
            Check.NotNull(entityType, nameof(entityType));

            var properties = new List <Dictionary <string, object> >();

            foreach (var property in entityType.GetProperties().OrderBy(p => p.GetColumnOrdinal()))
            {
                PropertyAnnotationsData = new List <Dictionary <string, object> >();

                if (UseDataAnnotations)
                {
                    GeneratePropertyDataAnnotations(property);
                }

                var propertyType = CSharpHelper.Reference(property.ClrType);
                if (_options?.Value?.EnableNullableReferenceTypes == true &&
                    property.IsNullable &&
                    !propertyType.EndsWith("?"))
                {
                    propertyType += "?";
                }
                properties.Add(new Dictionary <string, object>
                {
                    { "property-type", propertyType },
                    { "property-name", property.Name },
                    { "property-annotations", PropertyAnnotationsData },
                    { "property-comment", property.GetComment() },
                    { "property-isnullable", property.IsNullable },
                    { "nullable-reference-types", _options?.Value?.EnableNullableReferenceTypes == true }
                });
            }

            var transformedProperties = EntityTypeTransformationService.TransformProperties(properties);

            TemplateData.Add("properties", transformedProperties);
        }
Пример #30
0
        /// <summary>
        /// Generate OnModelBuilding method.
        /// </summary>
        /// <param name="model">Metadata about the shape of entities, the relationships between them, and how they map to the database.</param>
        /// <param name="useDataAnnotations">Use fluent modeling API if false.</param>
        protected virtual void GenerateOnModelCreating(IModel model, bool useDataAnnotations)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            var sb = new IndentedStringBuilder();

            using (sb.Indent())
            {
                sb.IncrementIndent();
                sb.AppendLine("protected override void OnModelCreating(ModelBuilder modelBuilder)");
                sb.Append("{");

                var annotations = model.GetAnnotations().ToList();
                RemoveAnnotation(ref annotations, ScaffoldingAnnotationNames.DatabaseName);
                RemoveAnnotation(ref annotations, ScaffoldingAnnotationNames.EntityTypeErrors);

                var annotationsToRemove = new List <IAnnotation>();
                annotationsToRemove.AddRange(annotations.Where(a => a.Name.StartsWith(RelationalAnnotationNames.SequencePrefix, StringComparison.Ordinal)));

                var lines = new List <string>();

                foreach (var annotation in annotations)
                {
                    if (CodeGenerator.IsHandledByConvention(model, annotation))
                    {
                        annotationsToRemove.Add(annotation);
                    }
                    else
                    {
#pragma warning disable CS0618 // Type or member is obsolete
                        var line = CodeGenerator.GenerateFluentApi(model, annotation, Language);
#pragma warning restore CS0618 // Type or member is obsolete

                        if (line != null)
                        {
                            lines.Add(line);
                            annotationsToRemove.Add(annotation);
                        }
                    }
                }

                lines.AddRange(GenerateAnnotations(annotations.Except(annotationsToRemove)));

                if (lines.Count > 0)
                {
                    using (sb.Indent())
                    {
                        sb.AppendLine();
                        sb.Append("modelBuilder" + lines[0]);

                        using (sb.Indent())
                        {
                            foreach (var line in lines.Skip(1))
                            {
                                sb.AppendLine();
                                sb.Append(line);
                            }
                        }

                        sb.AppendLine(";");
                    }
                }

                using (sb.Indent())
                {
                    if (HandlebarsScaffoldingOptions.RefineFluteAPI)
                    {
                        AllGenerateEntityTypeConfigurations(model, sb);
                    }
                    else
                    {
                        AllGenerateEntityTypes(model, useDataAnnotations, sb);
                    }

                    AllGenerateSequences(model, sb);

                    sb.AppendLine();
                    sb.AppendLine("OnModelCreatingExt(modelBuilder);");
                }

                sb.AppendLine("}");
                sb.AppendLine();
                sb.Append("partial void OnModelCreatingExt(ModelBuilder modelBuilder);");

                var onModelCreating = sb.ToString();
                TemplateData.Add("on-model-creating", onModelCreating);
            }
        }