public static DbContextQueryExtensionsClassDefinition GetDbContextQueryExtensionsClassDefinition(this ProjectFeature <EntityFrameworkCoreProjectSettings> projectFeature)
        {
            var project = projectFeature.GetEntityFrameworkCoreProject();

            var definition = new DbContextQueryExtensionsClassDefinition
            {
                Namespaces =
                {
                    "System",
                    "System.Collections.Generic",
                    "System.Linq",
                    "System.Threading.Tasks",
                    "Microsoft.EntityFrameworkCore",
                    project.GetDomainModelsNamespace()
                },
                Namespace      = project.Name,
                AccessModifier = AccessModifier.Public,
                IsStatic       = true,
                Name           = projectFeature.GetQueryExtensionsClassName()
            };

            foreach (var table in projectFeature.GetTables())
            {
                var selection = projectFeature.GetEntityFrameworkCoreProject().GetSelection(table);

                if (!project.Database.HasDefaultSchema(table))
                {
                    definition.Namespaces.AddUnique(project.GetDomainModelsNamespace(table.Schema));
                }

                if (selection.Settings.EntitiesWithDataContracts)
                {
                    definition.Namespaces.AddUnique(project.GetDomainQueryModelsNamespace());
                }

                definition.AddGetAllMethod(projectFeature, selection, table);

                if (table.PrimaryKey != null)
                {
                    definition.Methods.Add(GetGetMethod(projectFeature, selection, table));
                }

                foreach (var unique in table.Uniques)
                {
                    definition.Methods.Add(GetGetByUniqueMethods(projectFeature, table, unique));
                }

                if (selection.Settings.SimplifyDataTypes)
                {
                    definition.SimplifyDataTypes();
                }
            }

            return(definition);
        }
Пример #2
0
        private static MethodDefinition GetGetByUniqueMethods(ProjectFeature <EntityFrameworkCoreProjectSettings> projectFeature, ITable table, Unique unique)
        {
            var project = projectFeature.GetEntityFrameworkCoreProject();

            var selection = project.GetSelection(table);

            var expression = string.Format("item => {0}", string.Join(" && ", unique.Key.Select(item => string.Format("item.{0} == entity.{0}", project.CodeNamingConvention.GetPropertyName(item)))));

            var existingViews = project.Database.Views.Count(item => item.Name == table.Name);

            var genericTypeName = existingViews == 0 ? project.GetEntityName(table) : project.GetFullEntityName(table);
            var dbSetName       = existingViews == 0 ? project.GetDbSetPropertyName(table) : project.GetFullDbSetPropertyName(table);

            return(new MethodDefinition
            {
                AccessModifier = AccessModifier.Public,
                IsAsync = true,
                Type = string.Format("Task<{0}>", project.GetEntityName(table)),
                Name = project.GetGetByUniqueRepositoryMethodName(table, unique),
                Parameters =
                {
                    new ParameterDefinition(project.GetEntityName(table), "entity")
                },
                Lines =
                {
                    new CodeLine("return await DbContext.{0}.FirstOrDefaultAsync({1});", dbSetName, expression)
                }
            });
        }
        private static MethodDefinition GetGetAllMethod(ProjectFeature <EntityFrameworkCoreProjectSettings> projectFeature, IView view)
        {
            var project = projectFeature.GetEntityFrameworkCoreProject();

            var primaryKeys = project.Database
                              .Tables
                              .Where(item => item.PrimaryKey != null)
                              .Select(item => item.GetColumnsFromConstraint(item.PrimaryKey).Select(c => c.Name).First())
                              .ToList();

            var result = view.Columns.Where(item => primaryKeys.Contains(item.Name)).ToList();

            var parameters = new List <ParameterDefinition>();

            foreach (var pk in result)
            {
                parameters.Add(new ParameterDefinition(projectFeature.Project.Database.ResolveDatabaseType(pk), project.GetParameterName(pk), "null"));
            }

            var lines = new List <ILine>();

            if (parameters.Count == 0)
            {
                lines.Add(new CodeLine("return DbContext.{0};", project.GetDbSetPropertyName(view)));
            }
            else
            {
                lines.Add(new CodeLine("var query = DbContext.{0}.AsQueryable();", project.GetDbSetPropertyName(view)));
                lines.Add(new CodeLine());

                foreach (var pk in result)
                {
                    if (project.Database.ColumnIsNumber(pk))
                    {
                        lines.Add(new CodeLine("if ({0}.HasValue)", project.CodeNamingConvention.GetParameterName(pk.Name)));
                        lines.Add(new CodeLine(1, "query = query.Where(item => item.{0} == {1});", project.CodeNamingConvention.GetPropertyName(pk.Name), project.CodeNamingConvention.GetParameterName(pk.Name)));
                        lines.Add(new CodeLine());
                    }
                    else if (project.Database.ColumnIsString(pk))
                    {
                        lines.Add(new CodeLine("if (!string.IsNullOrEmpty({0}))", project.CodeNamingConvention.GetParameterName(pk.Name)));
                        lines.Add(new CodeLine(1, "query = query.Where(item => item.{0} == {1});", project.CodeNamingConvention.GetPropertyName(pk.Name), project.CodeNamingConvention.GetParameterName(pk.Name)));
                        lines.Add(new CodeLine());
                    }
                }

                lines.Add(new CodeLine("return query;"));
            }

            return(new MethodDefinition(AccessModifier.Public, string.Format("IQueryable<{0}>", project.GetEntityName(view)), project.GetGetAllRepositoryMethodName(view))
            {
                Parameters = parameters,
                Lines = lines
            });
        }
Пример #4
0
        private static MethodDefinition GetGetAllMethod(ProjectFeature <EntityFrameworkCoreProjectSettings> projectFeature, StoredProcedure storedProcedure)
        {
            var project = projectFeature.GetEntityFrameworkCoreProject();

            var parameters = new List <ParameterDefinition>();

            var lines = new List <ILine>()
            {
                new CommentLine(" Create query for stored procedure")
            };

            lines.Add(new CodeLine("var query = new"));
            lines.Add(new CodeLine("{"));
            lines.Add(new CodeLine(1, "Text = \" exec {0} {1} \",", project.Database.GetFullName(storedProcedure), string.Join(", ", storedProcedure.Parameters.Select(item => item.Name))));

            if (storedProcedure.Parameters.Count == 0)
            {
                lines.Add(new CodeLine(1, "Parameters = new object[] {}"));
            }
            else
            {
                lines.Add(new CodeLine(1, "Parameters = new[]"));
                lines.Add(new CodeLine(1, "{"));

                foreach (var parameter in storedProcedure.Parameters)
                {
                    var parameterName = project.CodeNamingConvention.GetParameterName(parameter.Name);

                    lines.Add(new CodeLine(2, "new SqlParameter(\"{0}\", {1}),", parameter.Name, parameterName));

                    parameters.Add(new ParameterDefinition(project.Database.ResolveDatabaseType(parameter), parameterName));
                }

                lines.Add(new CodeLine(1, "}"));
            }

            lines.Add(new CodeLine("};"));

            lines.Add(new EmptyLine());

            lines.Add(new ReturnLine("await DbContext"));
            lines.Add(new CodeLine(1, ".Query<{0}>()", project.GetEntityResultName(storedProcedure)));
            lines.Add(new CodeLine(1, ".FromSql(query.Text, query.Parameters)"));
            lines.Add(new CodeLine(1, ".ToListAsync();"));

            return(new MethodDefinition
            {
                AccessModifier = AccessModifier.Public,
                IsAsync = true,
                Type = string.Format("Task<IEnumerable<{0}>>", project.GetEntityResultName(storedProcedure)),
                Name = project.GetGetAllRepositoryMethodName(storedProcedure),
                Parameters = parameters,
                Lines = lines
            });
        }
Пример #5
0
        private static MethodDefinition GetGetMethod(ProjectFeature <EntityFrameworkCoreProjectSettings> projectFeature, ProjectSelection <EntityFrameworkCoreProjectSettings> projectSelection, ITable table)
        {
            var efCoreProject = projectFeature.GetEntityFrameworkCoreProject();

            var expression = string.Empty;

            if (table.Identity == null)
            {
                expression = string.Format("item => {0}", string.Join(" && ", table.PrimaryKey.Key.Select(item => string.Format("item.{0} == entity.{0}", efCoreProject.CodeNamingConvention.GetPropertyName(item)))));
            }
            else
            {
                expression = string.Format("item => item.{0} == entity.{0}", efCoreProject.CodeNamingConvention.GetPropertyName(table.Identity.Name));
            }

            if (projectSelection.Settings.EntitiesWithDataContracts)
            {
                var lines = new List <ILine>
                {
                    new CodeLine("return await DbContext.{0}", efCoreProject.GetDbSetPropertyName(table))
                };

                foreach (var foreignKey in table.ForeignKeys)
                {
                    var foreignTable = efCoreProject.Database.FindTable(foreignKey.References);

                    if (foreignKey == null)
                    {
                        continue;
                    }

                    lines.Add(new CodeLine(1, ".Include(p => p.{0})", foreignKey.GetParentNavigationProperty(foreignTable, efCoreProject).Name));
                }

                lines.Add(new CodeLine(1, ".FirstOrDefaultAsync({0});", expression));

                return(new MethodDefinition(string.Format("Task<{0}>", efCoreProject.GetEntityName(table)), efCoreProject.GetGetRepositoryMethodName(table), new ParameterDefinition(efCoreProject.GetEntityName(table), "entity"))
                {
                    IsAsync = true,
                    Lines = lines
                });
            }
            else
            {
                return(new MethodDefinition(string.Format("Task<{0}>", efCoreProject.GetEntityName(table)), efCoreProject.GetGetRepositoryMethodName(table), new ParameterDefinition(efCoreProject.GetEntityName(table), "entity"))
                {
                    IsAsync = true,
                    Lines =
                    {
                        new CodeLine("return await DbContext.{0}.FirstOrDefaultAsync({1});", efCoreProject.GetDbSetPropertyName(table), expression)
                    }
                });
            }
        }
        private static MethodDefinition GetGetAllMethodWithoutForeigns(ProjectFeature <EntityFrameworkCoreProjectSettings> projectFeature, ProjectSelection <EntityFrameworkCoreProjectSettings> projectSelection, ITable table)
        {
            var project = projectFeature.GetEntityFrameworkCoreProject();

            return(new MethodDefinition(AccessModifier.Public, string.Format("IQueryable<{0}>", project.GetEntityName(table)), project.GetGetAllRepositoryMethodName(table))
            {
                Lines =
                {
                    new CodeLine("return DbContext.{0};", project.GetDbSetPropertyName(table))
                }
            });
        }
Пример #7
0
        private static void GetGetAllMethod(this CSharpClassDefinition definition, ProjectFeature <EntityFrameworkCoreProjectSettings> projectFeature, IView view)
        {
            var efCoreProject = projectFeature.GetEntityFrameworkCoreProject();

            definition.Methods.Add(new MethodDefinition(string.Format("IQueryable<{0}>", efCoreProject.GetEntityName(view)), efCoreProject.GetGetAllRepositoryMethodName(view))
            {
                Lines =
                {
                    new CodeLine("return DbContext.{0};", efCoreProject.GetDbSetPropertyName(view))
                }
            });
        }
Пример #8
0
        private static MethodDefinition GetGetByUniqueMethods(ProjectFeature projectFeature, ITable table, Unique unique)
        {
            var entityFrameworkCoreProject = projectFeature.GetEntityFrameworkCoreProject();

            var expression = string.Format("item => {0}", string.Join(" && ", unique.Key.Select(item => string.Format("item.{0} == entity.{0}", NamingExtensions.namingConvention.GetPropertyName(item)))));

            return(new MethodDefinition(string.Format("Task<{0}>", table.GetSingularName()), table.GetGetByUniqueRepositoryMethodName(unique), new ParameterDefinition(table.GetSingularName(), "entity"))
            {
                IsAsync = true,
                Lines = new List <ILine>
                {
                    new CodeLine("return await DbContext.{0}.FirstOrDefaultAsync({1});", entityFrameworkCoreProject.Settings.DeclareDbSetPropertiesInDbContext ? table.GetPluralName() : string.Format("Set<{0}>()", table.GetSingularName()), expression)
                }
            });
        }
Пример #9
0
        private static MethodDefinition GetGetByUniqueMethods(ProjectFeature <EntityFrameworkCoreProjectSettings> projectFeature, ITable table, Unique unique)
        {
            var efCoreProject = projectFeature.GetEntityFrameworkCoreProject();

            var selection = efCoreProject.GetSelection(table);

            var expression = string.Format("item => {0}", string.Join(" && ", unique.Key.Select(item => string.Format("item.{0} == entity.{0}", efCoreProject.CodeNamingConvention.GetPropertyName(item)))));

            return(new MethodDefinition(string.Format("Task<{0}>", efCoreProject.GetEntityName(table)), efCoreProject.GetGetByUniqueRepositoryMethodName(table, unique), new ParameterDefinition(efCoreProject.GetEntityName(table), "entity"))
            {
                IsAsync = true,
                Lines =
                {
                    new CodeLine("return await DbContext.{0}.FirstOrDefaultAsync({1});", efCoreProject.GetDbSetPropertyName(table), expression)
                }
            });
        }
Пример #10
0
        private static MethodDefinition GetGetAllMethodWithoutForeigns(ProjectFeature <EntityFrameworkCoreProjectSettings> projectFeature, ProjectSelection <EntityFrameworkCoreProjectSettings> projectSelection, ITable table)
        {
            var project = projectFeature.GetEntityFrameworkCoreProject();

            var existingViews = project.Database.Views.Count(item => item.Name == table.Name);

            var genericTypeName = existingViews == 0 ? project.GetEntityName(table) : project.GetFullEntityName(table);
            var dbSetName       = existingViews == 0 ? project.GetDbSetPropertyName(table) : project.GetFullDbSetPropertyName(table);

            return(new MethodDefinition
            {
                AccessModifier = AccessModifier.Public,
                Type = string.Format("IQueryable<{0}>", genericTypeName),
                Name = project.GetGetAllRepositoryMethodName(table),
                Lines =
                {
                    new CodeLine("return DbContext.{0};", dbSetName)
                }
            });
        }
Пример #11
0
        public static RepositoryClassDefinition GetRepositoryClassDefinition(this ProjectFeature <EntityFrameworkCoreProjectSettings> projectFeature)
        {
            var project = projectFeature.GetEntityFrameworkCoreProject();

            var definition = new RepositoryClassDefinition
            {
                Namespaces =
                {
                    "System",
                    "System.Collections.Generic",
                    "System.Data.SqlClient",
                    "System.Linq",
                    "System.Threading.Tasks",
                    "Microsoft.EntityFrameworkCore"
                },
                Namespace      = project.GetDataLayerRepositoriesNamespace(),
                AccessModifier = AccessModifier.Public,
                Name           = projectFeature.GetClassRepositoryName(),
                BaseClass      = "Repository",
                Implements     =
                {
                    projectFeature.GetInterfaceRepositoryName()
                },
                Constructors =
                {
                    new ClassConstructorDefinition(AccessModifier.Public, new ParameterDefinition(project.GetDbContextName(project.Database), "dbContext"))
                    {
                        Invocation = "base(dbContext)"
                    }
                }
            };

            foreach (var table in project.Database.Tables)
            {
                definition.Namespaces
                .AddUnique(projectFeature.Project.Database.HasDefaultSchema(table) ? project.GetEntityLayerNamespace() : project.GetEntityLayerNamespace(table.Schema));

                definition.Namespaces.AddUnique(project.GetDataLayerContractsNamespace());
            }

            foreach (var table in projectFeature.GetTables())
            {
                var projectSelection = projectFeature.GetEntityFrameworkCoreProject().GetSelection(table);

                if (projectSelection.Settings.EntitiesWithDataContracts)
                {
                    definition.Namespaces.AddUnique(project.GetDataLayerDataContractsNamespace());
                }

                foreach (var foreignKey in table.ForeignKeys)
                {
                    if (string.IsNullOrEmpty(foreignKey.Child))
                    {
                        var child = projectFeature.Project.Database.FindTable(foreignKey.Child);

                        if (child != null)
                        {
                            definition.Namespaces.AddUnique(project.GetDataLayerDataContractsNamespace());
                        }
                    }
                }

                if (table.ForeignKeys.Count == 0)
                {
                    definition.Methods.Add(GetGetAllMethodWithoutForeigns(projectFeature, projectSelection, table));
                }
                else
                {
                    definition.GetGetAllMethod(projectFeature, projectSelection, table);
                }

                if (table.PrimaryKey != null)
                {
                    definition.Methods.Add(GetGetMethod(projectFeature, projectSelection, table));
                }

                foreach (var unique in table.Uniques)
                {
                    definition.Methods.Add(GetGetByUniqueMethods(projectFeature, table, unique));
                }

                if (projectSelection.Settings.SimplifyDataTypes)
                {
                    definition.SimplifyDataTypes();
                }
            }

            foreach (var view in projectFeature.GetViews())
            {
                var projectSelection = projectFeature.GetEntityFrameworkCoreProject().GetSelection(view);

                if (projectSelection.Settings.EntitiesWithDataContracts)
                {
                    definition.Namespaces.AddUnique(project.GetDataLayerDataContractsNamespace());
                }

                definition.Methods.Add(GetGetAllMethod(projectFeature, view));

                if (projectSelection.Settings.SimplifyDataTypes)
                {
                    definition.SimplifyDataTypes();
                }
            }

            foreach (var tableFunction in projectFeature.GetTableFunctions())
            {
                var projectSelection = projectFeature.GetEntityFrameworkCoreProject().GetSelection(tableFunction);

                definition.Methods.Add(GetGetAllMethod(projectFeature, tableFunction));

                if (projectSelection.Settings.SimplifyDataTypes)
                {
                    definition.SimplifyDataTypes();
                }
            }

            foreach (var storedProcedure in projectFeature.GetStoredProcedures())
            {
                var projectSelection = projectFeature.GetEntityFrameworkCoreProject().GetSelection(storedProcedure);

                definition.Methods.Add(GetGetAllMethod(projectFeature, storedProcedure));

                if (projectSelection.Settings.SimplifyDataTypes)
                {
                    definition.SimplifyDataTypes();
                }
            }

            return(definition);
        }
Пример #12
0
        public static RepositoryClassDefinition GetRepositoryClassDefinition(this ProjectFeature <EntityFrameworkCoreProjectSettings> projectFeature)
        {
            var efCoreProject = projectFeature.GetEntityFrameworkCoreProject();

            var definition = new RepositoryClassDefinition
            {
                Namespaces =
                {
                    "System",
                    "System.Linq",
                    "System.Threading.Tasks",
                    "Microsoft.EntityFrameworkCore"
                },
                Namespace  = efCoreProject.GetDataLayerRepositoriesNamespace(),
                Name       = projectFeature.GetClassRepositoryName(),
                BaseClass  = "Repository",
                Implements =
                {
                    projectFeature.GetInterfaceRepositoryName()
                },
                Constructors =
                {
                    new ClassConstructorDefinition(new ParameterDefinition(efCoreProject.GetDbContextName(efCoreProject.Database), "dbContext"))
                    {
                        Invocation = "base(dbContext)"
                    }
                }
            };

            foreach (var table in efCoreProject.Database.Tables)
            {
                definition.Namespaces
                .AddUnique(projectFeature.Project.Database.HasDefaultSchema(table) ? efCoreProject.GetEntityLayerNamespace() : efCoreProject.GetEntityLayerNamespace(table.Schema));

                definition.Namespaces.AddUnique(efCoreProject.GetDataLayerContractsNamespace());
            }

            var tables = projectFeature
                         .Project
                         .Database
                         .Tables
                         .Where(item => projectFeature.DbObjects.Select(dbo => dbo.FullName).Contains(item.FullName))
                         .ToList();

            foreach (var table in tables)
            {
                var projectSelection = projectFeature.GetEntityFrameworkCoreProject().GetSelection(table);

                if (projectSelection.Settings.EntitiesWithDataContracts)
                {
                    definition.Namespaces.AddUnique(efCoreProject.GetDataLayerDataContractsNamespace());
                }

                foreach (var foreignKey in table.ForeignKeys)
                {
                    if (string.IsNullOrEmpty(foreignKey.Child))
                    {
                        var child = projectFeature.Project.Database.FindTable(foreignKey.Child);

                        if (child != null)
                        {
                            definition.Namespaces.AddUnique(efCoreProject.GetDataLayerDataContractsNamespace());
                        }
                    }
                }

                if (table.ForeignKeys.Count == 0)
                {
                    definition.GetGetAllMethodWithoutForeigns(projectFeature, projectSelection, table);
                }
                else
                {
                    definition.GetGetAllMethod(projectFeature, projectSelection, table);
                }

                if (table.PrimaryKey != null)
                {
                    definition.Methods.Add(GetGetMethod(projectFeature, projectSelection, table));
                }

                foreach (var unique in table.Uniques)
                {
                    definition.Methods.Add(GetGetByUniqueMethods(projectFeature, table, unique));
                }

                if (projectSelection.Settings.SimplifyDataTypes)
                {
                    definition.SimplifyDataTypes();
                }
            }

            var views = projectFeature
                        .Project
                        .Database
                        .Views
                        .Where(item => projectFeature.DbObjects.Select(dbo => dbo.FullName).Contains(item.FullName))
                        .ToList();

            foreach (var view in views)
            {
                var projectSelection = projectFeature.GetEntityFrameworkCoreProject().GetSelection(view);

                if (projectSelection.Settings.EntitiesWithDataContracts)
                {
                    definition.Namespaces.AddUnique(efCoreProject.GetDataLayerDataContractsNamespace());
                }

                definition.GetGetAllMethod(projectFeature, view);

                if (projectSelection.Settings.SimplifyDataTypes)
                {
                    definition.SimplifyDataTypes();
                }
            }

            return(definition);
        }
Пример #13
0
        private static void GetGetAllMethod(this CSharpClassDefinition definition, ProjectFeature <EntityFrameworkCoreProjectSettings> projectFeature, ProjectSelection <EntityFrameworkCoreProjectSettings> projectSelection, ITable table)
        {
            var efCoreProject = projectFeature.GetEntityFrameworkCoreProject();

            var returnType = string.Empty;

            var lines = new List <ILine>();

            if (projectSelection.Settings.EntitiesWithDataContracts)
            {
                returnType = efCoreProject.GetDataContractName(table);

                var dataContractPropertiesSets = new[]
                {
                    new
                    {
                        IsForeign      = false,
                        Type           = string.Empty,
                        Nullable       = false,
                        ObjectSource   = string.Empty,
                        PropertySource = string.Empty,
                        Target         = string.Empty
                    }
                }.ToList();

                var entityAlias = NamingConvention.GetCamelCase(efCoreProject.GetEntityName(table));

                foreach (var column in table.Columns)
                {
                    var propertyName = column.GetPropertyName();

                    dataContractPropertiesSets.Add(new
                    {
                        IsForeign = false,
                        column.Type,
                        column.Nullable,
                        ObjectSource   = entityAlias,
                        PropertySource = propertyName,
                        Target         = propertyName
                    });
                }

                foreach (var foreignKey in table.ForeignKeys)
                {
                    var foreignTable = projectFeature.Project.Database.FindTable(foreignKey.References);

                    if (foreignTable == null)
                    {
                        continue;
                    }

                    var foreignKeyAlias = NamingConvention.GetCamelCase(efCoreProject.GetEntityName(foreignTable));

                    foreach (var column in foreignTable?.GetColumnsWithNoPrimaryKey())
                    {
                        if (dataContractPropertiesSets.Where(item => string.Format("{0}.{1}", item.ObjectSource, item.PropertySource) == string.Format("{0}.{1}", entityAlias, column.GetPropertyName())).Count() == 0)
                        {
                            var target = string.Format("{0}{1}", efCoreProject.GetEntityName(foreignTable), column.GetPropertyName());

                            dataContractPropertiesSets.Add(new
                            {
                                IsForeign = true,
                                column.Type,
                                column.Nullable,
                                ObjectSource   = foreignKeyAlias,
                                PropertySource = column.GetPropertyName(),
                                Target         = target
                            });
                        }
                    }
                }

                lines.Add(new CommentLine(" Get query from DbSet"));
                lines.Add(new CodeLine("var query = from {0} in DbContext.Set<{1}>()", entityAlias, efCoreProject.GetEntityName(table)));

                foreach (var foreignKey in table.ForeignKeys)
                {
                    var foreignTable = projectFeature.Project.Database.FindTable(foreignKey.References);

                    if (foreignTable == null)
                    {
                        continue;
                    }

                    var foreignKeyEntityName = efCoreProject.GetDbSetPropertyName(foreignTable);

                    var foreignKeyAlias = NamingConvention.GetCamelCase(efCoreProject.GetEntityName(foreignTable));

                    if (projectFeature.Project.Database.HasDefaultSchema(foreignTable))
                    {
                        definition.Namespaces.AddUnique(efCoreProject.GetEntityLayerNamespace());
                    }
                    else
                    {
                        definition.Namespaces.AddUnique(efCoreProject.GetEntityLayerNamespace(foreignTable.Schema));
                    }

                    if (foreignKey.Key.Count == 0)
                    {
                        lines.Add(new PreprocessorDirectiveLine(1, " There isn't definition for key in foreign key '{0}' in your current database", foreignKey.References));
                    }
                    else if (foreignKey.Key.Count == 1)
                    {
                        if (foreignTable == null)
                        {
                            lines.Add(LineHelper.Warning(" There isn't definition for '{0}' in your current database", foreignKey.References));
                        }
                        else
                        {
                            var column = table.Columns.FirstOrDefault(item => item.Name == foreignKey.Key.First());

                            var x = efCoreProject.CodeNamingConvention.GetPropertyName(foreignKey.Key.First());
                            var y = efCoreProject.CodeNamingConvention.GetPropertyName(foreignTable.PrimaryKey.Key.First());

                            if (column.Nullable)
                            {
                                lines.Add(new CodeLine(1, "join {0}Join in DbContext.{1} on {2}.{3} equals {0}Join.{4} into {0}Temp", foreignKeyAlias, foreignKeyEntityName, entityAlias, x, y));
                                lines.Add(new CodeLine(2, "from {0} in {0}Temp.DefaultIfEmpty()", foreignKeyAlias, entityAlias, x, y));
                            }
                            else
                            {
                                lines.Add(new CodeLine(1, "join {0} in DbContext.{1} on {2}.{3} equals {0}.{4}", foreignKeyAlias, foreignKeyEntityName, entityAlias, x, y));
                            }
                        }
                    }
                    else
                    {
                        lines.Add(LineHelper.Warning(" Add logic for foreign key with multiple key"));
                    }
                }

                lines.Add(new CodeLine(1, "select new {0}", returnType));
                lines.Add(new CodeLine(1, "{"));

                for (var i = 0; i < dataContractPropertiesSets.Count; i++)
                {
                    var property = dataContractPropertiesSets[i];

                    if (string.IsNullOrEmpty(property.ObjectSource) && string.IsNullOrEmpty(property.Target))
                    {
                        continue;
                    }

                    if (property.IsForeign)
                    {
                        var dbType = projectFeature.Project.Database.ResolveType(property.Type);

                        if (dbType == null)
                        {
                            throw new ObjectRelationMappingException(string.Format("There isn't mapping for '{0}' type", property.Type));
                        }

                        var clrType = dbType.GetClrType();

                        if (clrType.FullName == typeof(byte[]).FullName)
                        {
                            lines.Add(new CodeLine(2, "{0} = {1} == null ? default(byte[]) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                        }
                        else if (clrType.FullName == typeof(bool).FullName)
                        {
                            lines.Add(new CodeLine(2, "{0} = {1} == null ? default(bool?) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                        }
                        else if (clrType.FullName == typeof(string).FullName)
                        {
                            lines.Add(new CodeLine(2, "{0} = {1} == null ? string.Empty : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                        }
                        else if (clrType.FullName == typeof(DateTime).FullName)
                        {
                            lines.Add(new CodeLine(2, "{0} = {1} == null ? default(DateTime?) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                        }
                        else if (clrType.FullName == typeof(TimeSpan).FullName)
                        {
                            lines.Add(new CodeLine(2, "{0} = {1} == null ? default(TimeSpan?) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                        }
                        else if (clrType.FullName == typeof(byte).FullName)
                        {
                            lines.Add(new CodeLine(2, "{0} = {1} == null ? default(byte?) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                        }
                        else if (clrType.FullName == typeof(short).FullName)
                        {
                            lines.Add(new CodeLine(2, "{0} = {1} == null ? default(short?) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                        }
                        else if (clrType.FullName == typeof(int).FullName)
                        {
                            lines.Add(new CodeLine(2, "{0} = {1} == null ? default(int?) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                        }
                        else if (clrType.FullName == typeof(long).FullName)
                        {
                            lines.Add(new CodeLine(2, "{0} = {1} == null ? default(long?) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                        }
                        else if (clrType.FullName == typeof(decimal).FullName)
                        {
                            lines.Add(new CodeLine(2, "{0} = {1} == null ? default(decimal?) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                        }
                        else if (clrType.FullName == typeof(double).FullName)
                        {
                            lines.Add(new CodeLine(2, "{0} = {1} == null ? default(double?) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                        }
                        else if (clrType.FullName == typeof(float).FullName)
                        {
                            lines.Add(new CodeLine(2, "{0} = {1} == null ? default(float?) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                        }
                        else if (clrType.FullName == typeof(Guid).FullName)
                        {
                            lines.Add(new CodeLine(2, "{0} = {1} == null ? default(Guid?) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                        }
                        else
                        {
                            lines.Add(new CodeLine(2, "{0} = {1} == null ? default(object) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                        }
                    }
                    else
                    {
                        lines.Add(new CodeLine(2, "{0} = {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                    }
                }

                lines.Add(new CodeLine(1, "};"));
                lines.Add(new CodeLine());
            }
            else
            {
                returnType = efCoreProject.GetEntityName(table);

                lines.Add(new CommentLine(" Get query from DbSet"));
                lines.Add(new CodeLine("var query = DbContext.{0}.AsQueryable();", efCoreProject.GetDbSetPropertyName(table)));

                lines.Add(new CodeLine());
            }

            var parameters = new List <ParameterDefinition>();

            if (table.ForeignKeys.Count == 0)
            {
                lines.Add(new CodeLine("return query;"));
            }
            else
            {
                for (var i = 0; i < table.ForeignKeys.Count; i++)
                {
                    var foreignKey = table.ForeignKeys[i];

                    if (foreignKey.Key.Count == 1)
                    {
                        var column = table.Columns.First(item => item.Name == foreignKey.Key.First());

                        var parameterName = efCoreProject.GetParameterName(column);

                        parameters.Add(new ParameterDefinition(projectFeature.Project.Database.ResolveDatabaseType(column), parameterName, "null"));

                        if (projectFeature.Project.Database.ColumnIsDateTime(column))
                        {
                            lines.Add(new CommentLine(" Filter by: '{0}'", column.Name));
                            lines.Add(new CodeLine("if ({0}.HasValue)", parameterName));
                            lines.Add(new CodeLine(1, "query = query.Where(item => item.{0} == {1});", column.GetPropertyName(), parameterName));
                            lines.Add(new CodeLine());
                        }
                        else if (projectFeature.Project.Database.ColumnIsNumber(column))
                        {
                            lines.Add(new CommentLine(" Filter by: '{0}'", column.Name));
                            lines.Add(new CodeLine("if ({0}.HasValue)", parameterName));
                            lines.Add(new CodeLine(1, "query = query.Where(item => item.{0} == {1});", column.GetPropertyName(), parameterName));
                            lines.Add(new CodeLine());
                        }
                        else if (projectFeature.Project.Database.ColumnIsString(column))
                        {
                            lines.Add(new CommentLine(" Filter by: '{0}'", column.Name));
                            lines.Add(new CodeLine("if (!string.IsNullOrEmpty({0}))", parameterName));
                            lines.Add(new CodeLine(1, "query = query.Where(item => item.{0} == {1});", column.GetPropertyName(), parameterName));
                            lines.Add(new CodeLine());
                        }
                        else
                        {
                            lines.Add(new CommentLine(" Filter by: '{0}'", column.Name));
                            lines.Add(new CodeLine("if ({0} != null)", parameterName));
                            lines.Add(new CodeLine(1, "query = query.Where(item => item.{0} == {1});", column.GetPropertyName(), parameterName));
                            lines.Add(new CodeLine());
                        }
                    }
                    else
                    {
                        lines.Add(LineHelper.Warning("Add logic for foreign key with multiple key"));
                    }
                }

                lines.Add(new CodeLine("return query;"));
            }

            definition.Methods.Add(new MethodDefinition(string.Format("IQueryable<{0}>", returnType), efCoreProject.GetGetAllRepositoryMethodName(table), parameters.ToArray())
            {
                Lines = lines
            });
        }
        public static DbContextClassDefinition GetDbContextClassDefinition(this ProjectFeature <EntityFrameworkCoreProjectSettings> projectFeature, ProjectSelection <EntityFrameworkCoreProjectSettings> projectSelection)
        {
            var efCoreProject = projectFeature.GetEntityFrameworkCoreProject();

            var definition = new DbContextClassDefinition
            {
                Namespace = efCoreProject.GetDataLayerNamespace(),
                Name      = efCoreProject.GetDbContextName(efCoreProject.Database),
                BaseClass = "DbContext"
            };

            definition.Namespaces.AddUnique("System");
            definition.Namespaces.Add("Microsoft.EntityFrameworkCore");
            definition.Namespaces.Add(efCoreProject.GetEntityLayerNamespace());

            if (!projectSelection.Settings.UseDataAnnotations)
            {
                definition.Namespaces.Add(efCoreProject.GetDataLayerConfigurationsNamespace());
            }

            definition.Constructors.Add(new ClassConstructorDefinition(new ParameterDefinition(string.Format("DbContextOptions<{0}>", definition.Name), "options"))
            {
                Invocation = "base(options)"
            });

            definition.Methods.Add(GetOnModelCreatingMethod(efCoreProject));

            foreach (var table in projectFeature.Project.Database.Tables)
            {
                if (!projectFeature.Project.Database.HasDefaultSchema(table))
                {
                    definition.Namespaces.AddUnique(efCoreProject.GetEntityLayerNamespace(table.Schema));
                }

                definition.Properties.Add(new PropertyDefinition(string.Format("DbSet<{0}>", efCoreProject.GetEntityName(table)), efCoreProject.GetDbSetPropertyName(table)));
            }

            foreach (var view in projectFeature.Project.Database.Views)
            {
                if (!projectFeature.Project.Database.HasDefaultSchema(view))
                {
                    definition.Namespaces.AddUnique(efCoreProject.GetEntityLayerNamespace(view.Schema));
                }

                definition.Properties.Add(new PropertyDefinition(string.Format("DbSet<{0}>", efCoreProject.GetEntityName(view)), efCoreProject.GetDbSetPropertyName(view)));
            }

            foreach (var table in projectFeature.Project.Database.Tables)
            {
                if (!projectSelection.Settings.UseDataAnnotations && !projectFeature.Project.Database.HasDefaultSchema(table))
                {
                    definition.Namespaces.AddUnique(efCoreProject.GetDataLayerConfigurationsNamespace(table.Schema));
                }
            }

            foreach (var view in projectFeature.Project.Database.Views)
            {
                if (!projectSelection.Settings.UseDataAnnotations && !projectFeature.Project.Database.HasDefaultSchema(view))
                {
                    definition.Namespaces.AddUnique(efCoreProject.GetDataLayerConfigurationsNamespace(view.Schema));
                }
            }

            foreach (var scalarFunction in projectFeature.Project.Database.ScalarFunctions)
            {
                var parameterType = string.Empty;

                if (projectFeature.Project.Database.HasTypeMappedToClr(scalarFunction.Parameters[0]))
                {
                    var clrType = projectFeature.Project.Database.GetClrMapForType(scalarFunction.Parameters[0]);

                    parameterType = clrType.AllowClrNullable ? string.Format("{0}?", clrType.GetClrType().Name) : clrType.GetClrType().Name;
                }
                else
                {
                    parameterType = "object";
                }

                var method = new MethodDefinition
                {
                    Attributes =
                    {
                        new MetadataAttribute("DbFunction")
                        {
                            Sets =
                            {
                                new MetadataAttributeSet("FunctionName", string.Format("\"{0}\"", scalarFunction.Name)),
                                new MetadataAttributeSet("Schema",       string.Format("\"{0}\"", scalarFunction.Schema))
                            }
                        }
                    },
                    IsStatic = true,
                    Type     = parameterType,
                    Name     = efCoreProject.GetScalarFunctionMethodName(scalarFunction),
                    Lines    =
                    {
                        new CodeLine("throw new Exception();")
                    }
                };

                var parameters = scalarFunction.Parameters.Where(item => !string.IsNullOrEmpty(item.Name)).ToList();

                foreach (var parameter in parameters)
                {
                    parameterType = string.Empty;

                    if (projectFeature.Project.Database.HasTypeMappedToClr(parameter))
                    {
                        var clrType = projectFeature.Project.Database.GetClrMapForType(parameter);

                        parameterType = clrType.AllowClrNullable ? string.Format("{0}?", clrType.GetClrType().Name) : clrType.GetClrType().Name;
                    }
                    else
                    {
                        parameterType = "object";
                    }

                    method.Parameters.Add(new ParameterDefinition(parameterType, parameter.GetPropertyName()));
                }

                definition.Methods.Add(method);
            }

            if (projectSelection.Settings.SimplifyDataTypes)
            {
                definition.SimplifyDataTypes();
            }

            return(definition);
        }
        public static CSharpClassDefinition GetDbContextClassDefinition(this ProjectFeature projectFeature)
        {
            var classDefinition = new CSharpClassDefinition();

            classDefinition.Namespaces.Add("Microsoft.EntityFrameworkCore");

            classDefinition.Namespaces.Add(projectFeature.GetEntityFrameworkCoreProject().Settings.UseDataAnnotations ? projectFeature.GetEntityFrameworkCoreProject().GetEntityLayerNamespace() : projectFeature.GetEntityFrameworkCoreProject().GetDataLayerConfigurationsNamespace());

            classDefinition.Namespace = projectFeature.GetEntityFrameworkCoreProject().GetDataLayerNamespace();
            classDefinition.Name      = projectFeature.Project.Database.GetDbContextName();

            classDefinition.BaseClass = "DbContext";

            if (projectFeature.GetEntityFrameworkCoreProject().Settings.UseDataAnnotations)
            {
                classDefinition.Constructors.Add(new ClassConstructorDefinition(new ParameterDefinition(string.Format("DbContextOptions<{0}>", classDefinition.Name), "options"))
                {
                    Invocation = "base(options)"
                });
            }
            else
            {
                classDefinition.Constructors.Add(new ClassConstructorDefinition(new ParameterDefinition(string.Format("DbContextOptions<{0}>", classDefinition.Name), "options"), new ParameterDefinition("IEntityMapper", "entityMapper"))
                {
                    Invocation = "base(options)",
                    Lines      = new List <ILine>
                    {
                        new CodeLine("EntityMapper = entityMapper;")
                    }
                });
            }

            if (!projectFeature.GetEntityFrameworkCoreProject().Settings.UseDataAnnotations)
            {
                classDefinition.Properties.Add(new PropertyDefinition("IEntityMapper", "EntityMapper")
                {
                    IsReadOnly = true
                });
            }

            classDefinition.Methods.Add(GetOnModelCreatingMethod(projectFeature.GetEntityFrameworkCoreProject()));

            if (projectFeature.GetEntityFrameworkCoreProject().Settings.UseDataAnnotations)
            {
                foreach (var table in projectFeature.Project.Database.Tables)
                {
                    if (!table.HasDefaultSchema())
                    {
                        classDefinition.Namespaces.AddUnique(projectFeature.GetEntityFrameworkCoreProject().GetEntityLayerNamespace(table.Schema));
                    }

                    classDefinition.Properties.Add(new PropertyDefinition(string.Format("DbSet<{0}>", table.GetEntityName()), table.GetPluralName()));
                }

                foreach (var view in projectFeature.Project.Database.Views)
                {
                    if (!view.HasDefaultSchema())
                    {
                        classDefinition.Namespaces.AddUnique(projectFeature.GetEntityFrameworkCoreProject().GetEntityLayerNamespace(view.Schema));
                    }

                    classDefinition.Properties.Add(new PropertyDefinition(string.Format("DbSet<{0}>", view.GetEntityName()), view.GetPluralName()));
                }
            }

            return(classDefinition);
        }
Пример #16
0
 public static string GetQueryExtensionsClassName(this ProjectFeature <EntityFrameworkCoreProjectSettings> projectFeature)
 => string.Format("{0}{1}QueryExtensions",
                  projectFeature.GetEntityFrameworkCoreProject().GetDbContextName(projectFeature.Project.Database),
                  projectFeature.Project.CodeNamingConvention.GetClassName(projectFeature.Name)
                  );
Пример #17
0
        public static CSharpClassDefinition GetRepositoryClassDefinition(this ProjectFeature projectFeature)
        {
            var entityFrameworkCoreProject = projectFeature.GetEntityFrameworkCoreProject();

            var classDefinition = new CSharpClassDefinition();

            classDefinition.Namespaces.Add("System");
            classDefinition.Namespaces.Add("System.Linq");
            classDefinition.Namespaces.Add("System.Threading.Tasks");
            classDefinition.Namespaces.Add("Microsoft.EntityFrameworkCore");

            foreach (var table in entityFrameworkCoreProject.Database.Tables)
            {
                classDefinition.Namespaces.AddUnique(table.HasDefaultSchema() ? entityFrameworkCoreProject.GetEntityLayerNamespace() : entityFrameworkCoreProject.GetEntityLayerNamespace(table.Schema));

                classDefinition.Namespaces.AddUnique(entityFrameworkCoreProject.GetDataLayerContractsNamespace());
            }

            classDefinition.Namespace = entityFrameworkCoreProject.GetDataLayerRepositoriesNamespace();

            classDefinition.Name = projectFeature.GetClassRepositoryName();

            classDefinition.BaseClass = "Repository";

            classDefinition.Implements.Add(projectFeature.GetInterfaceRepositoryName());

            classDefinition.Constructors.Add(new ClassConstructorDefinition(new ParameterDefinition(projectFeature.Project.Database.GetDbContextName(), "dbContext"))
            {
                Invocation = "base(dbContext)"
            });

            var tables = projectFeature
                         .Project
                         .Database
                         .Tables
                         .Where(item => projectFeature.DbObjects.Select(dbo => dbo.FullName).Contains(item.FullName))
                         .ToList();

            foreach (var table in tables)
            {
                if (entityFrameworkCoreProject.Settings.EntitiesWithDataContracts.Contains(table.FullName))
                {
                    classDefinition.Namespaces.AddUnique(entityFrameworkCoreProject.GetDataLayerDataContractsNamespace());
                }

                foreach (var foreignKey in table.ForeignKeys)
                {
                    if (string.IsNullOrEmpty(foreignKey.Child))
                    {
                        var child = projectFeature.Project.Database.FindTableBySchemaAndName(foreignKey.Child);

                        if (child != null)
                        {
                            classDefinition.Namespaces.AddUnique(entityFrameworkCoreProject.GetDataLayerDataContractsNamespace());
                        }
                    }
                }

                classDefinition.GetGetAllMethod(projectFeature, table);

                if (table.PrimaryKey != null)
                {
                    classDefinition.Methods.Add(GetGetMethod(projectFeature, table));
                }

                foreach (var unique in table.Uniques)
                {
                    classDefinition.Methods.Add(GetGetByUniqueMethods(projectFeature, table, unique));
                }

                classDefinition.Methods.Add(GetAddMethod(projectFeature, table));

                if (table.PrimaryKey != null)
                {
                    classDefinition.Methods.Add(GetUpdateMethod(projectFeature, table));
                    classDefinition.Methods.Add(GetRemoveMethod(projectFeature, table));
                }
            }



            var views = projectFeature
                        .Project
                        .Database
                        .Views
                        .Where(item => projectFeature.DbObjects.Select(dbo => dbo.FullName).Contains(item.FullName))
                        .ToList();

            foreach (var view in views)
            {
                if (entityFrameworkCoreProject.Settings.EntitiesWithDataContracts.Contains(view.FullName))
                {
                    classDefinition.Namespaces.AddUnique(entityFrameworkCoreProject.GetDataLayerDataContractsNamespace());
                }

                classDefinition.GetGetAllMethod(projectFeature, view);
            }

            return(classDefinition);
        }
Пример #18
0
        private static void GetGetAllMethod(this CSharpClassDefinition classDefinition, ProjectFeature projectFeature, ITable table)
        {
            var entityFrameworkCoreProject = projectFeature.GetEntityFrameworkCoreProject();

            var returnType = string.Empty;

            var lines = new List <ILine>();

            if (entityFrameworkCoreProject.Settings.EntitiesWithDataContracts.Contains(table.FullName))
            {
                var entityAlias = NamingConvention.GetCamelCase(table.GetEntityName());

                returnType = table.GetDataContractName();

                var dataContractPropertiesSets = new[]
                {
                    new
                    {
                        IsForeign      = false,
                        Type           = string.Empty,
                        Nullable       = false,
                        ObjectSource   = string.Empty,
                        PropertySource = string.Empty,
                        Target         = string.Empty
                    }
                }.ToList();

                foreach (var column in table.Columns)
                {
                    var propertyName = column.GetPropertyName();

                    dataContractPropertiesSets.Add(new
                    {
                        IsForeign      = false,
                        Type           = column.Type,
                        Nullable       = column.Nullable,
                        ObjectSource   = entityAlias,
                        PropertySource = propertyName,
                        Target         = propertyName
                    });
                }

                foreach (var foreignKey in table.ForeignKeys)
                {
                    var foreignTable = projectFeature.Project.Database.FindTableByFullName(foreignKey.References);

                    if (foreignTable == null)
                    {
                        continue;
                    }

                    var foreignKeyAlias = NamingConvention.GetCamelCase(foreignTable.GetEntityName());

                    foreach (var column in foreignTable?.GetColumnsWithOutPrimaryKey())
                    {
                        if (dataContractPropertiesSets.Where(item => string.Format("{0}.{1}", item.ObjectSource, item.PropertySource) == string.Format("{0}.{1}", entityAlias, column.GetPropertyName())).Count() == 0)
                        {
                            var target = string.Format("{0}{1}", foreignTable.GetEntityName(), column.GetPropertyName());

                            dataContractPropertiesSets.Add(new
                            {
                                IsForeign      = true,
                                Type           = column.Type,
                                Nullable       = column.Nullable,
                                ObjectSource   = foreignKeyAlias,
                                PropertySource = column.GetPropertyName(),
                                Target         = target
                            });
                        }
                    }
                }

                lines.Add(new CommentLine(" Get query from DbSet"));
                lines.Add(new CodeLine("var query = from {0} in DbContext.Set<{1}>()", entityAlias, table.GetEntityName()));

                foreach (var foreignKey in table.ForeignKeys)
                {
                    var foreignTable = projectFeature.Project.Database.FindTableByFullName(foreignKey.References);

                    if (foreignTable == null)
                    {
                        continue;
                    }

                    var foreignKeyEntityName = foreignTable.GetEntityName();

                    var foreignKeyAlias = NamingConvention.GetCamelCase(foreignTable.GetEntityName());

                    if (foreignTable.HasDefaultSchema())
                    {
                        classDefinition.Namespaces.AddUnique(entityFrameworkCoreProject.GetEntityLayerNamespace());
                    }
                    else
                    {
                        classDefinition.Namespaces.AddUnique(entityFrameworkCoreProject.GetEntityLayerNamespace(foreignTable.Schema));
                    }

                    if (foreignKey.Key.Count == 0)
                    {
                        lines.Add(new PreprocessorDirectiveLine(1, " There isn't definition for key in foreign key '{0}' in your current database", foreignKey.References));
                    }
                    else if (foreignKey.Key.Count == 1)
                    {
                        if (foreignTable == null)
                        {
                            lines.Add(LineHelper.Warning(" There isn't definition for '{0}' in your current database", foreignKey.References));
                        }
                        else
                        {
                            var column = table.Columns.FirstOrDefault(item => item.Name == foreignKey.Key[0]);

                            var x = NamingExtensions.namingConvention.GetPropertyName(foreignKey.Key[0]);
                            var y = NamingExtensions.namingConvention.GetPropertyName(foreignTable.PrimaryKey.Key[0]);

                            if (column.Nullable)
                            {
                                lines.Add(new CodeLine(1, "join {0}Join in DbContext.Set<{1}>() on {2}.{3} equals {0}Join.{4} into {0}Temp", foreignKeyAlias, foreignKeyEntityName, entityAlias, x, y));
                                lines.Add(new CodeLine(2, "from {0} in {0}Temp.Where(relation => relation.{2} == {1}.{3}).DefaultIfEmpty()", foreignKeyAlias, entityAlias, x, y));
                            }
                            else
                            {
                                lines.Add(new CodeLine(1, "join {0} in DbContext.Set<{1}>() on {2}.{3} equals {0}.{4}", foreignKeyAlias, foreignKeyEntityName, entityAlias, x, y));
                            }
                        }
                    }
                    else
                    {
                        lines.Add(LineHelper.Warning(" Add logic for foreign key with multiple key"));
                    }
                }

                lines.Add(new CodeLine(1, "select new {0}", returnType));
                lines.Add(new CodeLine(1, "{"));

                for (var i = 0; i < dataContractPropertiesSets.Count; i++)
                {
                    var property = dataContractPropertiesSets[i];

                    if (string.IsNullOrEmpty(property.ObjectSource) && string.IsNullOrEmpty(property.Target))
                    {
                        continue;
                    }

                    if (property.IsForeign)
                    {
                        if (property.Type == "binary" || property.Type == "image" || property.Type == "varbinary")
                        {
                            if (property.Nullable)
                            {
                                lines.Add(new CodeLine(2, "{0} = {1} == null ? default(Byte[]) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                            else
                            {
                                lines.Add(new CodeLine(2, "{0} = {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                        }
                        else if (property.Type == "bit")
                        {
                            if (property.Nullable)
                            {
                                lines.Add(new CodeLine(2, "{0} = {1} == null ? default(Boolean?) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                            else
                            {
                                lines.Add(new CodeLine(2, "{0} = {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                        }
                        else if (property.Type.Contains("char") || property.Type.Contains("text"))
                        {
                            if (property.Nullable)
                            {
                                lines.Add(new CodeLine(2, "{0} = {1} == null ? string.Empty : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                            else
                            {
                                lines.Add(new CodeLine(2, "{0} = {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                        }
                        else if (property.Type.Contains("date"))
                        {
                            if (property.Nullable)
                            {
                                lines.Add(new CodeLine(2, "{0} = {1} == null ? default(DateTime?) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                            else
                            {
                                lines.Add(new CodeLine(2, "{0} = {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                        }
                        else if (property.Type == "tinyint")
                        {
                            if (property.Nullable)
                            {
                                lines.Add(new CodeLine(2, "{0} = {1} == null ? default(Byte?) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                            else
                            {
                                lines.Add(new CodeLine(2, "{0} = {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                        }
                        else if (property.Type == "smallint")
                        {
                            if (property.Nullable)
                            {
                                lines.Add(new CodeLine(2, "{0} = {1} == null ? default(Int16?) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                            else
                            {
                                lines.Add(new CodeLine(2, "{0} = {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                        }
                        else if (property.Type == "bigint")
                        {
                            if (property.Nullable)
                            {
                                lines.Add(new CodeLine(2, "{0} = {1} == null ? default(Int64?) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                            else
                            {
                                lines.Add(new CodeLine(2, "{0} = {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                        }
                        else if (property.Type == "int")
                        {
                            if (property.Nullable)
                            {
                                lines.Add(new CodeLine(2, "{0} = {1} == null ? default(Int32?) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                            else
                            {
                                lines.Add(new CodeLine(2, "{0} = {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                        }
                        else if (property.Type == "decimal" || property.Type == "money" || property.Type == "smallmoney")
                        {
                            if (property.Nullable)
                            {
                                lines.Add(new CodeLine(2, "{0} = {1} == null ? default(Decimal?) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                            else
                            {
                                lines.Add(new CodeLine(2, "{0} = {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                        }
                        else if (property.Type == "float")
                        {
                            if (property.Nullable)
                            {
                                lines.Add(new CodeLine(2, "{0} = {1} == null ? default(Double?) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                            else
                            {
                                lines.Add(new CodeLine(2, "{0} = {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                        }
                        else if (property.Type == "real")
                        {
                            if (property.Nullable)
                            {
                                lines.Add(new CodeLine(2, "{0} = {1} == null ? default(Single?) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                            else
                            {
                                lines.Add(new CodeLine(2, "{0} = {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                        }
                        else if (property.Type == "uniqueidentifier")
                        {
                            if (property.Nullable)
                            {
                                lines.Add(new CodeLine(2, "{0} = {1} == null ? default(Guid?) : {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                            else
                            {
                                lines.Add(new CodeLine(2, "{0} = {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                            }
                        }
                    }
                    else
                    {
                        lines.Add(new CodeLine(2, "{0} = {1}.{2},", property.Target, property.ObjectSource, property.PropertySource));
                    }
                }

                lines.Add(new CodeLine(1, "};"));
                lines.Add(new CodeLine());
            }
            else
            {
                returnType = table.GetSingularName();

                lines.Add(new CommentLine(" Get query from DbSet"));

                if (entityFrameworkCoreProject.Settings.DeclareDbSetPropertiesInDbContext)
                {
                    lines.Add(new CodeLine("var query = DbContext.{0}.AsQueryable();", table.GetPluralName()));
                }
                else
                {
                    lines.Add(new CodeLine("var query = DbContext.Set<{0}>().AsQueryable();", table.GetSingularName()));
                }

                lines.Add(new CodeLine());
            }

            var parameters = new List <ParameterDefinition>
            {
            };

            if (table.ForeignKeys.Count == 0)
            {
                lines.Add(new CodeLine("return query;"));
            }
            else
            {
                for (var i = 0; i < table.ForeignKeys.Count; i++)
                {
                    var foreignKey = table.ForeignKeys[i];

                    if (foreignKey.Key.Count == 1)
                    {
                        var column = table.Columns.First(item => item.Name == foreignKey.Key[0]);

                        var parameterName = NamingExtensions.namingConvention.GetParameterName(column.Name);

                        parameters.Add(new ParameterDefinition(column.GetClrType(), parameterName, "null"));

                        if (column.IsString())
                        {
                            lines.Add(new CodeLine("if (!string.IsNullOrEmpty({0}))", NamingExtensions.namingConvention.GetParameterName(column.Name)));
                            lines.Add(new CodeLine("{"));
                            lines.Add(new CommentLine(1, " Filter by: '{0}'", column.Name));
                            lines.Add(new CodeLine(1, "query = query.Where(item => item.{0} == {1});", column.GetPropertyName(), parameterName));
                            lines.Add(new CodeLine("}"));
                            lines.Add(new CodeLine());
                        }
                        else
                        {
                            lines.Add(new CodeLine("if ({0}.HasValue)", NamingExtensions.namingConvention.GetParameterName(column.Name)));
                            lines.Add(new CodeLine("{"));
                            lines.Add(new CommentLine(1, " Filter by: '{0}'", column.Name));
                            lines.Add(new CodeLine(1, "query = query.Where(item => item.{0} == {1});", column.GetPropertyName(), parameterName));
                            lines.Add(new CodeLine("}"));
                            lines.Add(new CodeLine());
                        }
                    }
                    else
                    {
                        lines.Add(LineHelper.Warning("Add logic for foreign key with multiple key"));
                    }
                }

                lines.Add(new CodeLine("return query;"));
            }

            classDefinition.Methods.Add(new MethodDefinition(string.Format("IQueryable<{0}>", returnType), table.GetGetAllRepositoryMethodName(), parameters.ToArray())
            {
                Lines = lines
            });
        }
Пример #19
0
        private static MethodDefinition GetGetMethod(ProjectFeature <EntityFrameworkCoreProjectSettings> projectFeature, ProjectSelection <EntityFrameworkCoreProjectSettings> projectSelection, ITable table)
        {
            var project = projectFeature.GetEntityFrameworkCoreProject();

            var expression = string.Empty;

            if (table.Identity == null)
            {
                expression = string.Format("item => {0}", string.Join(" && ", table.PrimaryKey.Key.Select(item => string.Format("item.{0} == entity.{0}", project.CodeNamingConvention.GetPropertyName(item)))));
            }
            else
            {
                expression = string.Format("item => item.{0} == entity.{0}", project.CodeNamingConvention.GetPropertyName(table.Identity.Name));
            }

            var existingViews = project.Database.Views.Count(item => item.Name == table.Name);

            var genericTypeName = existingViews == 0 ? project.GetEntityName(table) : project.GetFullEntityName(table);
            var dbSetName       = existingViews == 0 ? project.GetDbSetPropertyName(table, projectSelection.Settings.PluralizeDbSetPropertyNames) : project.GetFullDbSetPropertyName(table);

            if (projectSelection.Settings.EntitiesWithDataContracts)
            {
                var lines = new List <ILine>
                {
                    new CodeLine("return await DbContext.{0}", dbSetName)
                };

                if (projectSelection.Settings.DeclareNavigationProperties)
                {
                    foreach (var foreignKey in table.ForeignKeys)
                    {
                        var foreignTable = project.Database.FindTable(foreignKey.References);

                        if (foreignKey == null)
                        {
                            continue;
                        }

                        lines.Add(new CodeLine(1, ".Include(p => p.{0})", foreignKey.GetParentNavigationProperty(foreignTable, project).Name));
                    }
                }

                lines.Add(new CodeLine(1, ".FirstOrDefaultAsync({0});", expression));

                return(new MethodDefinition
                {
                    AccessModifier = AccessModifier.Public,
                    IsAsync = true,
                    Type = string.Format("Task<{0}>", project.GetEntityName(table)),
                    Name = project.GetGetRepositoryMethodName(table),
                    Parameters =
                    {
                        new ParameterDefinition(project.GetEntityName(table), "entity")
                    },
                    Lines = lines
                });
            }
            else
            {
                return(new MethodDefinition
                {
                    AccessModifier = AccessModifier.Public,
                    IsAsync = true,
                    Type = string.Format("Task<{0}>", project.GetEntityName(table)),
                    Name = project.GetGetRepositoryMethodName(table),
                    Parameters =
                    {
                        new ParameterDefinition(project.GetEntityName(table), "entity")
                    },
                    Lines =
                    {
                        new CodeLine("return await DbContext.{0}.FirstOrDefaultAsync({1});", dbSetName, expression)
                    }
                });
            }
        }
Пример #20
0
 public static string GetRepositoryInterfaceName(this ProjectFeature <EntityFrameworkCoreProjectSettings> projectFeature)
 => projectFeature
 .GetEntityFrameworkCoreProject()
 .CodeNamingConvention
 .GetInterfaceName(string.Format("{0}Repository", projectFeature.Name));