Example #1
0
        /// <summary>
        /// <summary>Generates code for a model.</summary>
        /// </summary>
        /// <param name="model"> The model.</param>
        /// <param name="options"> The options to use during generation. </param>
        /// <returns> The generated model. </returns>
        public override ScaffoldedModel GenerateModel(IModel model, ModelCodeGenerationOptions options)
        {
            Check.NotNull(model, nameof(model));
            Check.NotNull(options, nameof(options));

            // Register Hbs helpers and partial templates
            HandlebarsHelperService.RegisterHelpers();
            HandlebarsBlockHelperService.RegisterBlockHelpers();
            DbContextTemplateService.RegisterPartialTemplates();
            EntityTypeTemplateService.RegisterPartialTemplates();

            var resultingFiles = new ScaffoldedModel();

            string generatedCode;

            if (!(CSharpDbContextGenerator is NullCSharpDbContextGenerator))
            {
                generatedCode = CSharpDbContextGenerator.WriteCode(
                    model,
                    options.ContextName,
                    options.ConnectionString,
                    options.ContextNamespace,
                    options.ModelNamespace,
                    options.UseDataAnnotations,
                    options.SuppressConnectionStringWarning);

                var dbContextFileName = options.ContextName + FileExtension;
                resultingFiles.ContextFile = new ScaffoldedFile
                {
                    Path = options.ContextDir != null
                        ? Path.Combine(options.ContextDir, dbContextFileName)
                        : dbContextFileName,
                    Code = generatedCode
                };
            }

            if (!(CSharpEntityTypeGenerator is NullCSharpEntityTypeGenerator))
            {
                foreach (var entityType in model.GetScaffoldEntityTypes(_options.Value))
                {
                    generatedCode = CSharpEntityTypeGenerator.WriteCode(
                        entityType,
                        options.ModelNamespace,
                        options.UseDataAnnotations);

                    var transformedFileName = EntityTypeTransformationService.TransformEntityFileName(entityType.DisplayName());
                    var entityTypeFileName  = transformedFileName + FileExtension;
                    resultingFiles.AdditionalFiles.Add(
                        new ScaffoldedFile
                    {
                        Path = entityTypeFileName,
                        Code = generatedCode
                    });
                }
            }

            return(resultingFiles);
        }
Example #2
0
        /// <summary>
        /// Reverse engineer DbContext and entity type files from an existing database.
        /// </summary>
        /// <param name="model">Metadata about the shape of entities, the relationships between them, and how they map to the database.</param>
        /// <param name="outputPath">File path for the generated files.</param>
        /// <param name="namespace">Namespace for generated classes.</param>
        /// <param name="contextName">DbContext name.</param>
        /// <param name="connectionString">Database connection string.</param>
        /// <param name="useDataAnnotations">Generate classes using data annotations.</param>
        /// <returns></returns>
        public override ReverseEngineerFiles WriteCode(
            IModel model,
            string outputPath,
            string @namespace,
            string contextName,
            string connectionString,
            bool useDataAnnotations)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            if (outputPath == null)
            {
                throw new ArgumentNullException(nameof(outputPath));
            }
            if (@namespace == null)
            {
                throw new ArgumentNullException(nameof(@namespace));
            }
            if (contextName == null)
            {
                throw new ArgumentNullException(nameof(contextName));
            }
            if (connectionString == null)
            {
                throw new ArgumentNullException(nameof(connectionString));
            }

            // Register Hbs helpers and partial templates
            DbContextTemplateService.RegisterHelper(Constants.SpacesHelper, HandlebarsHelpers.GetSpacesHelper());
            DbContextTemplateService.RegisterPartialTemplates();
            EntityTypeTemplateService.RegisterPartialTemplates();

            ReverseEngineerFiles reverseEngineerFiles = new ReverseEngineerFiles();

            if (!(CSharpDbContextGenerator is NullCSharpDbContextGenerator))
            {
                string contents1 = CSharpDbContextGenerator.WriteCode(model, @namespace, contextName, connectionString, useDataAnnotations);
                string fileName1 = contextName + FileExtension;
                string str1      = FileService.OutputFile(outputPath, fileName1, contents1);
                reverseEngineerFiles.ContextFile = str1;
            }

            if (!(CSharpEntityTypeGenerator is NullCSharpEntityTypeGenerator))
            {
                foreach (IEntityType entityType in model.GetEntityTypes())
                {
                    string contents2 = CSharpEntityTypeGenerator.WriteCode(entityType, @namespace, useDataAnnotations);
                    string fileName2 = entityType.DisplayName() + FileExtension;
                    string str2      = FileService.OutputFile(outputPath, fileName2, contents2);
                    reverseEngineerFiles.EntityTypeFiles.Add(str2);
                }
            }

            return(reverseEngineerFiles);
        }
    public override ScaffoldedModel GenerateModel(IModel model, ModelCodeGenerationOptions options)
    {
        if (options.ContextName == null)
        {
            throw new ArgumentException(
                      CoreStrings.ArgumentPropertyNull(nameof(options.ContextName), nameof(options)), nameof(options));
        }

        if (options.ConnectionString == null)
        {
            throw new ArgumentException(
                      CoreStrings.ArgumentPropertyNull(nameof(options.ConnectionString), nameof(options)), nameof(options));
        }

        var resultingFiles = new ScaffoldedModel();

        var contextTemplate = Path.Combine(options.ProjectDir !, TemplatesDirectory, "DbContext.t4");

        Check.DebugAssert(_host.Session == null, "Session is not null.");
        _host.Session = _host.CreateSession();
        try
        {
            _host.Session.Add("Model", model);
            _host.Session.Add("Options", options);
            _host.Session.Add("NamespaceHint", options.ContextNamespace ?? options.ModelNamespace);
            _host.Session.Add("ProjectDefaultNamespace", options.RootNamespace);

            var handler       = new TextTemplatingCallback();
            var generatedCode = ProcessTemplate(contextTemplate, handler);

            var dbContextFileName = options.ContextName + handler.Extension;
            resultingFiles.ContextFile = new ScaffoldedFile
            {
                Path = options.ContextDir != null
                    ? Path.Combine(options.ContextDir, dbContextFileName)
                    : dbContextFileName,
                Code = generatedCode
            };
        }
        finally
        {
            _host.Session = null;
        }

        var entityTypeTemplate = Path.Combine(options.ProjectDir !, TemplatesDirectory, "EntityType.t4");

        if (File.Exists(entityTypeTemplate))
        {
            foreach (var entityType in model.GetEntityTypes())
            {
                // TODO: Should this be handled inside the template?
                if (CSharpDbContextGenerator.IsManyToManyJoinEntityType(entityType))
                {
                    continue;
                }

                _host.Session = _host.CreateSession();
                try
                {
                    _host.Session.Add("EntityType", entityType);
                    _host.Session.Add("Options", options);
                    _host.Session.Add("NamespaceHint", options.ModelNamespace);
                    _host.Session.Add("ProjectDefaultNamespace", options.RootNamespace);

                    var handler       = new TextTemplatingCallback();
                    var generatedCode = ProcessTemplate(entityTypeTemplate, handler);
                    if (string.IsNullOrWhiteSpace(generatedCode))
                    {
                        continue;
                    }

                    var entityTypeFileName = entityType.Name + handler.Extension;
                    resultingFiles.AdditionalFiles.Add(
                        new ScaffoldedFile {
                        Path = entityTypeFileName, Code = generatedCode
                    });
                }
                finally
                {
                    _host.Session = null;
                }
            }
        }

        return(resultingFiles);
    }
Example #4
0
        /// <summary>Generates code for a model.</summary>
        /// <param name="model"> The model. </param>
        /// <param name="namespace"> The namespace. </param>
        /// <param name="contextDir"> The directory of the <see cref="T:Microsoft.EntityFrameworkCore.DbContext" />. </param>
        /// <param name="contextName"> The name of the <see cref="T:Microsoft.EntityFrameworkCore.DbContext" />. </param>
        /// <param name="connectionString"> The connection string. </param>
        /// <param name="options"> The options to use during generation. </param>
        /// <returns> The generated model. </returns>
        public override ScaffoldedModel GenerateModel(IModel model,
                                                      string @namespace,
                                                      string contextDir,
                                                      string contextName,
                                                      string connectionString,
                                                      ModelCodeGenerationOptions options)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }
            if (string.IsNullOrWhiteSpace(@namespace))
            {
                throw new ArgumentNullException(nameof(@namespace));
            }
            if (contextDir == null)
            {
                throw new ArgumentNullException(nameof(contextDir));
            }
            if (string.IsNullOrWhiteSpace(contextName))
            {
                throw new ArgumentNullException(nameof(contextName));
            }
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw new ArgumentNullException(nameof(connectionString));
            }
            if (contextDir == null)
            {
                throw new ArgumentNullException(nameof(contextDir));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            // Register Hbs helpers and partial templates
            HandlebarsHelperService.RegisterHelpers();
            DbContextTemplateService.RegisterPartialTemplates();
            EntityTypeTemplateService.RegisterPartialTemplates();

            var resultingFiles = new ScaffoldedModel();

            string generatedCode;

            if (!(CSharpDbContextGenerator is NullCSharpDbContextGenerator))
            {
                generatedCode = CSharpDbContextGenerator.WriteCode(model, @namespace, contextName, connectionString, options.UseDataAnnotations, options.SuppressConnectionStringWarning);

                var dbContextFileName = contextName + FileExtension;
                resultingFiles.ContextFile = new ScaffoldedFile {
                    Path = Path.Combine(contextDir, dbContextFileName), Code = generatedCode
                };
            }

            if (!(CSharpEntityTypeGenerator is NullCSharpEntityTypeGenerator))
            {
                foreach (var entityType in model.GetEntityTypes())
                {
                    generatedCode = CSharpEntityTypeGenerator.WriteCode(entityType, @namespace, options.UseDataAnnotations);

                    var transformedFileName = EntityTypeTransformationService.TransformEntityFileName(entityType.DisplayName());
                    var entityTypeFileName  = transformedFileName + FileExtension;
                    resultingFiles.AdditionalFiles.Add(new ScaffoldedFile {
                        Path = entityTypeFileName, Code = generatedCode
                    });
                }
            }

            return(resultingFiles);
        }
    /// <summary>
    ///     This is an internal API that supports the Entity Framework Core infrastructure and not subject to
    ///     the same compatibility standards as public APIs. It may be changed or removed without notice in
    ///     any release. You should only use it directly in your code with extreme caution and knowing that
    ///     doing so can result in application failures when updating to a new Entity Framework Core release.
    /// </summary>
    public override ScaffoldedModel GenerateModel(
        IModel model,
        ModelCodeGenerationOptions options)
    {
        if (options.ContextName == null)
        {
            throw new ArgumentException(
                      CoreStrings.ArgumentPropertyNull(nameof(options.ContextName), nameof(options)), nameof(options));
        }

        if (options.ConnectionString == null)
        {
            throw new ArgumentException(
                      CoreStrings.ArgumentPropertyNull(nameof(options.ConnectionString), nameof(options)), nameof(options));
        }

        var generatedCode = CSharpDbContextGenerator.WriteCode(
            model,
            options.ContextName,
            options.ConnectionString,
            options.ContextNamespace,
            options.ModelNamespace,
            options.UseDataAnnotations,
            options.UseNullableReferenceTypes,
            options.SuppressConnectionStringWarning,
            options.SuppressOnConfiguring);

        // output DbContext .cs file
        var dbContextFileName = options.ContextName + FileExtension;
        var resultingFiles    = new ScaffoldedModel
        {
            ContextFile = new ScaffoldedFile
            {
                Path = options.ContextDir != null
                    ? Path.Combine(options.ContextDir, dbContextFileName)
                    : dbContextFileName,
                Code = generatedCode
            }
        };

        foreach (var entityType in model.GetEntityTypes())
        {
            if (Internal.CSharpDbContextGenerator.IsManyToManyJoinEntityType(entityType))
            {
                continue;
            }

            generatedCode = CSharpEntityTypeGenerator.WriteCode(
                entityType,
                options.ModelNamespace,
                options.UseDataAnnotations,
                options.UseNullableReferenceTypes);

            // output EntityType poco .cs file
            var entityTypeFileName = entityType.Name + FileExtension;
            resultingFiles.AdditionalFiles.Add(
                new ScaffoldedFile {
                Path = entityTypeFileName, Code = generatedCode
            });
        }

        return(resultingFiles);
    }