diff --git a/src/OSharp.CodeConsoles/Data/AutoMapperConfiguration.cs b/src/OSharp.CodeConsoles/Data/AutoMapperConfiguration.cs new file mode 100644 index 0000000000000000000000000000000000000000..8430baef6cbeb086c9a87639e79549fcbf005c37 --- /dev/null +++ b/src/OSharp.CodeConsoles/Data/AutoMapperConfiguration.cs @@ -0,0 +1,33 @@ +// ----------------------------------------------------------------------- +// +// Copyright (c) 2014-2021 OSharp. All rights reserved. +// +// http://www.osharp.org +// 郭明锋 +// 2021-04-06 13:13 +// ----------------------------------------------------------------------- + +using Microsoft.Extensions.DependencyInjection; + +using OSharp.AutoMapper; +using OSharp.CodeGeneration.Services.Entities; +using OSharp.Dependency; + + +namespace OSharp.CodeConsoles.Data +{ + [Dependency(ServiceLifetime.Singleton)] + public class AutoMapperConfiguration : AutoMapperTupleBase + { + /// 创建对象映射 + public override void CreateMap() + { + CreateMap().ForMember(vm => vm.Namespace, opt => opt.Ignore()) + .ForMember(vm => vm.Project, opt => opt.Ignore()); + + CreateMap().ForMember(vm => vm.Module, opt => opt.Ignore()); + + CreateMap().ForMember(vm => vm.Entity, opt => opt.Ignore()); + } + } +} diff --git a/src/OSharp.CodeConsoles/Data/DesignTimeDefaultDbContextFactory.cs b/src/OSharp.CodeConsoles/Data/DesignTimeDefaultDbContextFactory.cs new file mode 100644 index 0000000000000000000000000000000000000000..e24ebeaffcb57f22563200e37b40a6ee1fc5081e --- /dev/null +++ b/src/OSharp.CodeConsoles/Data/DesignTimeDefaultDbContextFactory.cs @@ -0,0 +1,42 @@ +// ----------------------------------------------------------------------- +// +// Copyright (c) 2014-2020 OSharp. All rights reserved. +// +// http://www.osharp.org +// 郭明锋 +// 2020-08-25 23:16 +// ----------------------------------------------------------------------- + +using System; + +using Microsoft.Extensions.DependencyInjection; + +using OSharp.Entity; + + +namespace OSharp.CodeConsoles.Data +{ + public class DesignTimeDefaultDbContextFactory : DesignTimeDbContextFactoryBase + { + public DesignTimeDefaultDbContextFactory() + : base(null) + { } + + public DesignTimeDefaultDbContextFactory(IServiceProvider serviceProvider) + : base(serviceProvider) + { } + + /// + /// 创建设计时使用的ServiceProvider,主要用于执行 Add-Migration 功能 + /// + /// + protected override IServiceProvider CreateDesignTimeServiceProvider() + { + IServiceCollection services = new ServiceCollection(); + Startup startup = new Startup(); + startup.ConfigureServices(services); + IServiceProvider provider = services.BuildServiceProvider(); + return provider; + } + } +} diff --git a/src/OSharp.CodeConsoles/Data/SqliteDefaultDbContextMigrationPack.cs b/src/OSharp.CodeConsoles/Data/SqliteDefaultDbContextMigrationPack.cs new file mode 100644 index 0000000000000000000000000000000000000000..78cff41b65aeb4b3025be668afc697df792af6e1 --- /dev/null +++ b/src/OSharp.CodeConsoles/Data/SqliteDefaultDbContextMigrationPack.cs @@ -0,0 +1,39 @@ +using System; +using System.ComponentModel; + +using OSharp.Core.Packs; +using OSharp.Entity; +using OSharp.Entity.Sqlite; + + +namespace OSharp.CodeConsoles.Data +{ + /// + /// Sqlite-DefaultDbContext迁移模块 + /// + [DependsOnPacks(typeof(SqliteEntityFrameworkCorePack))] + [Description("Sqlite-DefaultDbContext迁移模块")] + public class SqliteDefaultDbContextMigrationPack : MigrationPackBase + { + /// + /// 获取 模块启动顺序,模块启动的顺序先按级别启动,级别内部再按此顺序启动, + /// 级别默认为0,表示无依赖,需要在同级别有依赖顺序的时候,再重写为>0的顺序值 + /// + public override int Order => 2; + + /// + /// 获取 数据库类型 + /// + protected override DatabaseType DatabaseType => DatabaseType.Sqlite; + + /// + /// 重写实现获取数据上下文实例 + /// + /// 服务提供者 + /// + protected override DefaultDbContext CreateDbContext(IServiceProvider scopedProvider) + { + return new DesignTimeDefaultDbContextFactory(scopedProvider).CreateDbContext(new string[0]); + } + } +} diff --git a/src/OSharp.CodeConsoles/Data/Startup.cs b/src/OSharp.CodeConsoles/Data/Startup.cs new file mode 100644 index 0000000000000000000000000000000000000000..cb9e61d8ed2ada2b16825540ba21b5081a5d3bb0 --- /dev/null +++ b/src/OSharp.CodeConsoles/Data/Startup.cs @@ -0,0 +1,41 @@ +// ----------------------------------------------------------------------- +// +// Copyright (c) 2014-2020 OSharp. All rights reserved. +// +// http://www.osharp.org +// 郭明锋 +// 2020-08-26 10:26 +// ----------------------------------------------------------------------- + +using System; + +using Microsoft.Extensions.DependencyInjection; + +using OSharp.AutoMapper; +using OSharp.CodeGeneration.Generates; +using OSharp.CodeGeneration.Services; +using OSharp.Entity; +using OSharp.Entity.Sqlite; +using OSharp.Log4Net; + + +namespace OSharp.CodeConsoles.Data +{ + public class Startup + { + public void ConfigureServices(IServiceCollection services) + { + services.AddOSharp() + .AddPack() + .AddPack() + .AddPack() + .AddPack() + .AddPack(); + } + + public void Configure(IServiceProvider provider) + { + provider.UseOsharp(); + } + } +} diff --git a/src/OSharp.CodeConsoles/OSharp.CodeConsoles.csproj b/src/OSharp.CodeConsoles/OSharp.CodeConsoles.csproj index 5071d8d7ccb63db573a935889681454df6215068..1b58a47e7802d519a5203876fb590a8aa5038226 100644 --- a/src/OSharp.CodeConsoles/OSharp.CodeConsoles.csproj +++ b/src/OSharp.CodeConsoles/OSharp.CodeConsoles.csproj @@ -7,6 +7,13 @@ + + + + + + Always + diff --git a/src/OSharp.CodeConsoles/Program.cs b/src/OSharp.CodeConsoles/Program.cs index 6a9251cef60825c94bd83652f39a5833e7613565..f5ee0314585789e55ad9fed7975f3dd98685207e 100644 --- a/src/OSharp.CodeConsoles/Program.cs +++ b/src/OSharp.CodeConsoles/Program.cs @@ -1,18 +1,35 @@ using System; +using System.Collections.Generic; using System.Diagnostics; +using System.IO; +using System.Linq; + +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; using MiniRazor; +using OSharp.CodeConsoles.Data; +using OSharp.CodeGeneration.Generates; +using OSharp.CodeGeneration.Services; using OSharp.CodeGeneration.Services.Entities; using OSharp.CodeGeneration.Templates; +using OSharp.Data; +using OSharp.Entity; +using OSharp.Extensions; +using OSharp.Json; namespace OSharp.CodeConsoles { class Program { + private static ServiceProvider _provider; + static void Main(string[] args) { + Init(); + bool exit = false; while (true) { @@ -80,14 +97,18 @@ namespace OSharp.CodeConsoles } } + private static void Init() + { + IServiceCollection services = new ServiceCollection(); + Startup startup = new Startup(); + startup.ConfigureServices(services); + _provider = services.BuildServiceProvider(); + startup.Configure(_provider); + } + private static async void Method01() { - var model = new CodeModule { Name = "Infos" }; - await TestTemplate.RenderAsync(Console.Out, model); - ITemplate tmp = new TestTemplate(); - tmp.Model = model; - tmp.Output = Console.Out; - await tmp.ExecuteAsync(); + } private static async void Method02() @@ -139,9 +160,33 @@ namespace OSharp.CodeConsoles throw new NotImplementedException(); } - private static void Method11() + private static async void Method11() { - throw new NotImplementedException(); + Console.WriteLine("请输入代码模板:"); + string input = Console.ReadLine(); + CodeProject project = null; + CodeTemplate template = null; + await _provider.ExecuteScopedWorkAsync(async provider => + { + IDataContract contract = provider.GetService(); + CodeProject[] projects = contract.GetCodeProject(m => true); + project = projects[0]; + template = contract.CodeTemplates.FirstOrDefault(m => m.Name == input); + }); + + if (template == null) + { + Console.WriteLine($"模板 {input} 不存在"); + return; + } + ICodeGenerator generator = _provider.GetService(); + + //var model = project.Modules.First().Entities.First(); + //var model = project.Modules.First(); + var model = project; + CodeFile file = await generator.GenerateCode(template, model); + File.WriteAllText(@"D:\Temp\11.txt", file.SourceCode); + Console.WriteLine(file.SourceCode); } } } diff --git a/src/OSharp.CodeConsoles/appsettings.json b/src/OSharp.CodeConsoles/appsettings.json new file mode 100644 index 0000000000000000000000000000000000000000..ebd3b082c1d5f0f6576b240c42b1d3a188e3d4db --- /dev/null +++ b/src/OSharp.CodeConsoles/appsettings.json @@ -0,0 +1,14 @@ +{ + "OSharp": { + "DbContexts": { + "Sqlite": { + "DbContextTypeName": "OSharp.Entity.DefaultDbContext,OSharp.EntityFrameworkCore", + "ConnectionString": "data source=d:/temp/osharp-code-generator.db", + "DatabaseType": "Sqlite", + "LazyLoadingProxiesEnabled": true, + "AuditEntityEnabled": false, + "AutoMigrationEnabled": true + } + } + } +} diff --git a/src/OSharp.CodeGeneration/Generates/CodeFile.cs b/src/OSharp.CodeGeneration/Generates/CodeFile.cs index b7f11ec34ed37434064e0a66b4a67c47e71599e9..e511049dfe557d4a2eefbf64d75f9ad3520fcb35 100644 --- a/src/OSharp.CodeGeneration/Generates/CodeFile.cs +++ b/src/OSharp.CodeGeneration/Generates/CodeFile.cs @@ -7,6 +7,7 @@ // 2021-04-08 21:39 // ----------------------------------------------------------------------- +using OSharp.CodeGeneration.Services.Entities; using OSharp.Extensions; @@ -22,7 +23,7 @@ namespace OSharp.CodeGeneration.Generates /// /// 获取或设置 代码配置 /// - public GenCodeConfig CodeConfig { get; set; } + public CodeTemplate Template { get; set; } /// /// 获取或设置 源代码字符串 diff --git a/src/OSharp.CodeGeneration/Generates/ICodeGenerator.cs b/src/OSharp.CodeGeneration/Generates/ICodeGenerator.cs index ad2f1b3ef8a5c4a3b082088592849f9b91712215..fe41452b6568360b8edf5d28f7adec21d4491fd5 100644 --- a/src/OSharp.CodeGeneration/Generates/ICodeGenerator.cs +++ b/src/OSharp.CodeGeneration/Generates/ICodeGenerator.cs @@ -25,27 +25,27 @@ namespace OSharp.CodeGeneration.Generates /// 要处理的代码配置集合 /// 代码项目信息 /// 输出的代码文件信息集合 - Task GenerateCodes(GenCodeConfig[] codeConfigs, CodeProject project); + Task GenerateCodes(CodeTemplate[] codeConfigs, CodeProject project); /// /// 生成项目元数据相关代码 /// 代码配置 /// 项目元数据 /// - Task GenerateCode(GenCodeConfig codeConfig, CodeProject project); + Task GenerateCode(CodeTemplate codeConfig, CodeProject project); /// /// 生成模块元数据相关代码 /// 代码配置 /// 模块元数据 /// - Task GenerateCode(GenCodeConfig codeConfig, CodeModule module); + Task GenerateCode(CodeTemplate codeConfig, CodeModule module); /// /// 生成实体元数据相关代码 /// 代码配置 /// 实体元数据 /// - Task GenerateCode(GenCodeConfig codeConfig, CodeEntity entity); + Task GenerateCode(CodeTemplate codeConfig, CodeEntity entity); } } diff --git a/src/OSharp.CodeGeneration/Generates/RazorCodeGenerator.cs b/src/OSharp.CodeGeneration/Generates/RazorCodeGenerator.cs index b87e169498cf244e3a7a13b877502288f60d234a..7b95496ab340a354516151a187fff4ce56be8afe 100644 --- a/src/OSharp.CodeGeneration/Generates/RazorCodeGenerator.cs +++ b/src/OSharp.CodeGeneration/Generates/RazorCodeGenerator.cs @@ -30,34 +30,34 @@ namespace OSharp.CodeGeneration.Generates /// /// 生成项目所有代码 /// - /// 要处理的代码配置集合 + /// 要处理的代码配置集合 /// 代码项目信息 /// 输出的代码文件信息集合 - public async Task GenerateCodes(GenCodeConfig[] codeConfigs, CodeProject project) + public async Task GenerateCodes(CodeTemplate[] templates, CodeProject project) { List codeFiles = new List(); CodeModule[] modules = project.Modules.ToArray(); CodeEntity[] entities = modules.SelectMany(m => m.Entities).ToArray(); - foreach (GenCodeConfig codeConfig in codeConfigs.Where(m => m.MetadataType == MetadataType.Entity)) + foreach (CodeTemplate template in templates.Where(m => m.MetadataType == MetadataType.Entity)) { foreach (CodeEntity entity in entities) { - codeFiles.Add(await GenerateCode(codeConfig, entity)); + codeFiles.Add(await GenerateCode(template, entity)); } } - foreach (GenCodeConfig codeConfig in codeConfigs.Where(m => m.MetadataType == MetadataType.Module)) + foreach (CodeTemplate template in templates.Where(m => m.MetadataType == MetadataType.Module)) { foreach (CodeModule module in modules) { - codeFiles.Add(await GenerateCode(codeConfig, module)); + codeFiles.Add(await GenerateCode(template, module)); } } - foreach (GenCodeConfig codeConfig in codeConfigs.Where(m => m.MetadataType == MetadataType.Project)) + foreach (CodeTemplate template in templates.Where(m => m.MetadataType == MetadataType.Project)) { - codeFiles.Add(await GenerateCode(codeConfig, project)); + codeFiles.Add(await GenerateCode(template, project)); } return codeFiles.OrderBy(m => m.FileName).ToArray(); @@ -65,73 +65,74 @@ namespace OSharp.CodeGeneration.Generates /// /// 生成项目元数据相关代码 - /// 代码配置 + /// 代码配置 /// 项目元数据 /// - public Task GenerateCode(GenCodeConfig codeConfig, CodeProject project) + public Task GenerateCode(CodeTemplate template, CodeProject project) { - string fileName = codeConfig.GetCodeFileName(project); - return GenerateCodeCore(codeConfig, project, fileName); + string fileName = template.GetCodeFileName(project); + return GenerateCodeCore(template, project, fileName); } /// /// 生成模块元数据相关代码 - /// 代码配置 + /// 代码配置 /// 模块元数据 /// - public Task GenerateCode(GenCodeConfig codeConfig, CodeModule module) + public Task GenerateCode(CodeTemplate template, CodeModule module) { - string fileName = codeConfig.GetCodeFileName(module); - return GenerateCodeCore(codeConfig, module, fileName); + string fileName = template.GetCodeFileName(module); + return GenerateCodeCore(template, module, fileName); } /// /// 生成实体元数据相关代码 - /// 代码配置 + /// 代码配置 /// 实体元数据 /// - public Task GenerateCode(GenCodeConfig codeConfig, CodeEntity entity) + public Task GenerateCode(CodeTemplate template, CodeEntity entity) { - string fileName = codeConfig.GetCodeFileName(entity); - return GenerateCodeCore(codeConfig, entity, fileName); + string fileName = template.GetCodeFileName(entity); + return GenerateCodeCore(template, entity, fileName); } /// /// 生成代码 /// - /// 代码配置 + /// 代码配置 /// 代码数据模型 /// 代码输出文件 /// - protected virtual async Task GenerateCodeCore(GenCodeConfig codeConfig, object model, string fileName) + protected virtual async Task GenerateCodeCore(CodeTemplate template, object model, string fileName) { StringBuilder sb = new StringBuilder(); await using TextWriter writer = new StringWriter(sb); - if (codeConfig.TemplateType == null) + if (template.TemplateFile == "内置") { - if (codeConfig.TemplateFile == null || !File.Exists(codeConfig.TemplateFile)) + Type innerTemplateType = template.GetInnerTemplateType(); + ITemplate template2 = (ITemplate)(Activator.CreateInstance(innerTemplateType) + ?? throw new OsharpException($"代码配置“{template.Name}”的模板类型实例化失败")); + template2.Model = model; + template2.Output = writer; + await template2.ExecuteAsync(); + } + else + { + if (template.TemplateFile == null || !File.Exists(template.TemplateFile)) { - throw new OsharpException($"代码配置“{codeConfig.Name}”的模板文件“{codeConfig.TemplateFile}”不存在"); + throw new OsharpException($"代码配置“{template.Name}”的模板文件“{template.TemplateFile}”不存在"); } - string templateSource = await File.ReadAllTextAsync(codeConfig.TemplateFile); + string templateSource = await File.ReadAllTextAsync(template.TemplateFile); TemplateDescriptor descriptor = Razor.Compile(templateSource); await descriptor.RenderAsync(writer, model); } - else - { - ITemplate template = (ITemplate)(Activator.CreateInstance(codeConfig.TemplateType) - ?? throw new OsharpException($"代码配置“{codeConfig.Name}”的模板类型实例化失败")); - template.Model = model; - template.Output = writer; - await template.ExecuteAsync(); - } string codeSource = sb.ToString(); CodeFile codeFile = new CodeFile() { - CodeConfig = codeConfig, + Template = template, SourceCode = codeSource, FileName = fileName }; diff --git a/src/OSharp.CodeGeneration/OSharp.CodeGeneration.csproj b/src/OSharp.CodeGeneration/OSharp.CodeGeneration.csproj index e7d80575cf64b73b07ccdea2f4df2b4e37c84840..732a470541e6555f49f0ca616109c4020e9f7ce9 100644 --- a/src/OSharp.CodeGeneration/OSharp.CodeGeneration.csproj +++ b/src/OSharp.CodeGeneration/OSharp.CodeGeneration.csproj @@ -6,8 +6,8 @@ - - + + @@ -21,6 +21,23 @@ + + + + + + + + + + + + + + + + + <_Parameter1>OSharp.CodeConsoles diff --git a/src/OSharp.CodeGeneration/Services/DataPack.cs b/src/OSharp.CodeGeneration/Services/DataPack.cs index 0a01300c96ad2e7126747bc00e9018e94e901217..79741cfcaac36e45edca992e81965269b7aaafbe 100644 --- a/src/OSharp.CodeGeneration/Services/DataPack.cs +++ b/src/OSharp.CodeGeneration/Services/DataPack.cs @@ -1,6 +1,8 @@ using Microsoft.Extensions.DependencyInjection; +using OSharp.CodeGeneration.Services.Seeds; using OSharp.Core.Packs; +using OSharp.Entity; namespace OSharp.CodeGeneration.Services @@ -13,6 +15,11 @@ namespace OSharp.CodeGeneration.Services public override IServiceCollection AddServices(IServiceCollection services) { services.AddScoped(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); return base.AddServices(services); } diff --git a/src/OSharp.CodeGeneration/Services/DataService.CodeEntity.cs b/src/OSharp.CodeGeneration/Services/DataService.CodeEntity.cs index a6f182d2d351daa6a2d281b47996dc7a0a1d258f..f003ba5c407a69e0ae8a6c19882d73706afaac86 100644 --- a/src/OSharp.CodeGeneration/Services/DataService.CodeEntity.cs +++ b/src/OSharp.CodeGeneration/Services/DataService.CodeEntity.cs @@ -13,6 +13,7 @@ using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; +using OSharp.CodeGeneration.Services.Dtos; using OSharp.CodeGeneration.Services.Entities; using OSharp.Collections; using OSharp.Data; @@ -43,50 +44,55 @@ namespace OSharp.CodeGeneration.Services /// /// 更新代码实体信息信息 /// - /// 包含更新信息的代码实体信息DTO信息 + /// 包含更新信息的代码实体信息DTO信息 /// 业务操作结果 - public async Task UpdateCodeEntities(params CodeEntity[] entities) + public async Task UpdateCodeEntities(params CodeEntityInputDto[] dtos) { List names = new List(); UnitOfWork.EnableTransaction(); - foreach (var entity in entities) + foreach (var dto in dtos) { - entity.Validate(); - CodeModule module = await ModuleRepository.GetAsync(entity.ModuleId); + dto.Validate(); + CodeModule module = await ModuleRepository.GetAsync(dto.ModuleId); if (module == null) { - return new OperationResult(OperationResultType.Error, $"编号为“{entity.ModuleId}”的模块信息不存在"); + return new OperationResult(OperationResultType.Error, $"编号为“{dto.ModuleId}”的模块信息不存在"); } - if (await CheckCodeEntityExists(m => m.Name == entity.Name && m.ModuleId == entity.ModuleId, entity.Id)) + if (await CheckCodeEntityExists(m => m.Name == dto.Name && m.ModuleId == dto.ModuleId, dto.Id)) { - return new OperationResult(OperationResultType.Error, $"模块“{module.Name}”中名称为“{entity.Name}”的实体信息已存在"); + return new OperationResult(OperationResultType.Error, $"模块“{module.Name}”中名称为“{dto.Name}”的实体信息已存在"); } + if (dto.Order == 0) + { + dto.Order = EntityRepository.Query(m => m.ModuleId == module.Id).Count() + 1; + } int count; - if (entity.Id == default) + if (dto.Id == default) { + CodeEntity entity = dto.MapTo(); count = await EntityRepository.InsertAsync(entity); } else { - CodeEntity existing = await EntityRepository.GetAsync(entity.Id); - existing = entity.MapTo(existing); - count = await EntityRepository.UpdateAsync(existing); + CodeEntity entity = await EntityRepository.GetAsync(dto.Id); + entity = dto.MapTo(entity); + count = await EntityRepository.UpdateAsync(entity); } if (count > 0) { - names.Add(entity.Name); + names.Add(dto.Name); } } await UnitOfWork.CommitAsync(); return names.Count > 0 - ? new OperationResult(OperationResultType.Success, $"实体“{names.ExpandAndToString()}”更新成功") + ? new OperationResult(OperationResultType.Success, $"实体“{names.ExpandAndToString()}”保存成功") : OperationResult.NoChanged; } - + /// /// 删除代码实体信息信息 /// diff --git a/src/OSharp.CodeGeneration/Services/DataService.CodeForeign.cs b/src/OSharp.CodeGeneration/Services/DataService.CodeForeign.cs index 3ea4f9039978fcfdffa62c27f0b91539e9df4f42..527b09b4aa950174a06d6520d891a52975a61af4 100644 --- a/src/OSharp.CodeGeneration/Services/DataService.CodeForeign.cs +++ b/src/OSharp.CodeGeneration/Services/DataService.CodeForeign.cs @@ -13,6 +13,7 @@ using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; +using OSharp.CodeGeneration.Services.Dtos; using OSharp.CodeGeneration.Services.Entities; using OSharp.Collections; using OSharp.Data; @@ -39,44 +40,45 @@ namespace OSharp.CodeGeneration.Services { return ForeignRepository.CheckExistsAsync(predicate, id); } - + /// /// 更新实体外键信息信息 /// - /// 包含更新信息的实体外键信息 + /// 包含更新信息的实体外键信息 /// 业务操作结果 - public async Task UpdateCodeForeigns(params CodeForeign[] foreigns) + public async Task UpdateCodeForeigns(params CodeForeignInputDto[] dtos) { List names = new List(); UnitOfWork.EnableTransaction(); - foreach (var foreign in foreigns) + foreach (var dto in dtos) { - foreign.Validate(); - CodeEntity entity = await EntityRepository.GetAsync(foreign.EntityId); + dto.Validate(); + CodeEntity entity = await EntityRepository.GetAsync(dto.EntityId); if (entity == null) { - return new OperationResult(OperationResultType.Error, $"编号为“{foreign.EntityId}”的实体信息不存在"); + return new OperationResult(OperationResultType.Error, $"编号为“{dto.EntityId}”的实体信息不存在"); } - if (await CheckCodeForeignExists(m => m.SelfNavigation == foreign.SelfNavigation && m.EntityId == foreign.EntityId, entity.Id)) + if (await CheckCodeForeignExists(m => m.SelfNavigation == dto.SelfNavigation && m.EntityId == dto.EntityId, entity.Id)) { - return new OperationResult(OperationResultType.Error, $"实体“{entity.Name}”中名称为“{foreign.SelfNavigation}”的外键信息已存在"); + return new OperationResult(OperationResultType.Error, $"实体“{entity.Name}”中名称为“{dto.SelfNavigation}”的外键信息已存在"); } int count; - if (foreign.Id == default) + if (dto.Id == default) { + CodeForeign foreign = dto.MapTo(); count = await ForeignRepository.InsertAsync(foreign); } else { - CodeForeign existing = await ForeignRepository.GetAsync(foreign.Id); - existing = foreign.MapTo(existing); - count = await ForeignRepository.UpdateAsync(existing); + CodeForeign foreign = await ForeignRepository.GetAsync(dto.Id); + foreign = dto.MapTo(foreign); + count = await ForeignRepository.UpdateAsync(foreign); } if (count > 0) { - names.Add($"{entity.Name}-{foreign.SelfNavigation}"); + names.Add($"{entity.Name}-{dto.SelfNavigation}"); } } diff --git a/src/OSharp.CodeGeneration/Services/DataService.CodeModule.cs b/src/OSharp.CodeGeneration/Services/DataService.CodeModule.cs index d53819aa9abe87b50776363a741c7bf566565849..dc7f917c2771bfa6cc4ee7e673573c4e74220a47 100644 --- a/src/OSharp.CodeGeneration/Services/DataService.CodeModule.cs +++ b/src/OSharp.CodeGeneration/Services/DataService.CodeModule.cs @@ -13,6 +13,7 @@ using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; +using OSharp.CodeGeneration.Services.Dtos; using OSharp.CodeGeneration.Services.Entities; using OSharp.Collections; using OSharp.Data; @@ -39,78 +40,55 @@ namespace OSharp.CodeGeneration.Services { return ModuleRepository.CheckExistsAsync(predicate, id); } - + /// - /// 添加代码模块信息信息 + /// 更新代码模块信息信息 /// - /// 要添加的代码模块信息 + /// 包含更新信息的代码模块信息DTO信息 /// 业务操作结果 - public async Task CreateCodeModules(params CodeModule[] modules) + public async Task UpdateCodeModules(params CodeModuleInputDto[] dtos) { List names = new List(); UnitOfWork.EnableTransaction(); - foreach (CodeModule module in modules) + foreach (var dto in dtos) { - module.Validate(); - CodeProject project = await ProjectRepository.GetAsync(module.ProjectId); + dto.Validate(); + CodeProject project = await ProjectRepository.GetAsync(dto.ProjectId); if (project == null) { - return new OperationResult(OperationResultType.Error, $"编号为“{module.ProjectId}”的项目信息不存在"); + return new OperationResult(OperationResultType.Error, $"编号为“{dto.ProjectId}”的项目信息不存在"); } - if (await CheckCodeModuleExists(m => m.Name == module.Name && m.ProjectId == module.ProjectId)) + if (await CheckCodeModuleExists(m => m.Name == dto.Name && m.ProjectId == dto.ProjectId, dto.Id)) { - return new OperationResult(OperationResultType.Error, $"项目“{project.Name}”中名称为“{module.Name}”的模块信息已存在"); + return new OperationResult(OperationResultType.Error, $"项目“{project.Name}”中名称为“{dto.Name}”的模块信息已存在"); } - int count = await ModuleRepository.InsertAsync(module); - if (count > 0) + if (dto.Order == 0) { - names.Add(module.Name); + dto.Order = ModuleRepository.Query(m => m.ProjectId == dto.ProjectId).Count() + 1; } - } - - await UnitOfWork.CommitAsync(); - return names.Count > 0 - ? new OperationResult(OperationResultType.Success, $"模块“{names.ExpandAndToString()}”创建成功") - : OperationResult.NoChanged; - } - - /// - /// 更新代码模块信息信息 - /// - /// 包含更新信息的代码模块信息 - /// 业务操作结果 - public async Task UpdateCodeModules(params CodeModule[] modules) - { - List names = new List(); - UnitOfWork.EnableTransaction(); - foreach (CodeModule module in modules) - { - module.Validate(); - CodeProject project = await ProjectRepository.GetAsync(module.ProjectId); - if (project == null) + int count; + if (dto.Id == default) { - return new OperationResult(OperationResultType.Error, $"编号为“{module.ProjectId}”的项目信息不存在"); + CodeModule module = dto.MapTo(); + count = await ModuleRepository.InsertAsync(module); } - - if (await CheckCodeModuleExists(m => m.Name == module.Name && m.ProjectId == module.ProjectId, module.Id)) + else { - return new OperationResult(OperationResultType.Error, $"项目“{project.Name}”中名称为“{module.Name}”的模块信息已存在"); + CodeModule module = await ModuleRepository.GetAsync(dto.Id); + module = dto.MapTo(module); + count = await ModuleRepository.UpdateAsync(module); } - - CodeModule existing = await ModuleRepository.GetAsync(module.Id); - existing = module.MapTo(existing); - int count = await ModuleRepository.UpdateAsync(existing); if (count > 0) { - names.Add(module.Name); + names.Add(dto.Name); } } await UnitOfWork.CommitAsync(); return names.Count > 0 - ? new OperationResult(OperationResultType.Success, $"模块“{names.ExpandAndToString()}”更新成功") + ? new OperationResult(OperationResultType.Success, $"模块“{names.ExpandAndToString()}”保存成功") : OperationResult.NoChanged; } @@ -149,5 +127,6 @@ namespace OSharp.CodeGeneration.Services ? new OperationResult(OperationResultType.Success, $"模块“{names.ExpandAndToString()}”删除成功") : OperationResult.NoChanged; } + } } diff --git a/src/OSharp.CodeGeneration/Services/DataService.CodeProject.cs b/src/OSharp.CodeGeneration/Services/DataService.CodeProject.cs index 2ba894dcd7825aaa5f9ea9a521ba25849e00de94..b28ae47193169e44ef7e8e25e73c21ab6fb7848e 100644 --- a/src/OSharp.CodeGeneration/Services/DataService.CodeProject.cs +++ b/src/OSharp.CodeGeneration/Services/DataService.CodeProject.cs @@ -4,10 +4,13 @@ using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; +using OSharp.CodeGeneration.Services.Dtos; using OSharp.CodeGeneration.Services.Entities; using OSharp.Collections; using OSharp.Data; using OSharp.Extensions; +using OSharp.Json; +using OSharp.Mapping; namespace OSharp.CodeGeneration.Services @@ -30,23 +33,55 @@ namespace OSharp.CodeGeneration.Services return ProjectRepository.CheckExistsAsync(predicate, id); } + /// + /// 获取指定条件的项目信息 + /// + /// 检查谓语表达式 + /// 项目信息集合 + public CodeProject[] GetCodeProject(Expression> predicate) + { + CodeProject[] projects = ProjectRepository.Query(predicate).ToArray(); + string json = projects.ToJsonString(); + projects = json.FromJsonString(); + foreach (CodeProject project in projects) + { + foreach (CodeModule module in project.Modules.OrderBy(m => m.Order)) + { + foreach (CodeEntity entity in module.Entities.OrderBy(m => m.Order)) + { + foreach (CodeProperty property in entity.Properties.OrderBy(m => m.Order)) + { + property.Entity = entity; + } + + entity.Module = module; + } + + module.Project = project; + } + } + + return projects; + } + /// /// 添加项目信息信息 /// - /// 要添加的项目信息 + /// 要添加的项目信息DTO信息 /// 业务操作结果 - public async Task CreateCodeProjects(params CodeProject[] projects) + public async Task CreateCodeProjects(params CodeProjectInputDto[] dtos) { List names = new List(); UnitOfWork.EnableTransaction(); - foreach (CodeProject project in projects) + foreach (var dto in dtos) { - project.Validate(); - if (await CheckCodeProjectExists(m => m.Name == project.Name)) + dto.Validate(); + if (await CheckCodeProjectExists(m => m.Name == dto.Name)) { - return new OperationResult(OperationResultType.Error, $"名称为“{project.Name}”的项目信息已存在"); + return new OperationResult(OperationResultType.Error, $"名称为“{dto.Name}”的项目信息已存在"); } + CodeProject project = dto.MapTo(); int count = await ProjectRepository.InsertAsync(project); if (count > 0) { @@ -63,24 +98,27 @@ namespace OSharp.CodeGeneration.Services /// /// 更新项目信息信息 /// - /// 包含更新信息的项目信息 + /// 包含更新信息的项目信息DTO信息 /// 业务操作结果 - public async Task UpdateCodeProjects(params CodeProject[] projects) + public async Task UpdateCodeProjects(params CodeProjectInputDto[] dtos) { + List names = new List(); UnitOfWork.EnableTransaction(); - foreach (CodeProject project in projects) + foreach (var dto in dtos) { - project.Validate(); - if (await CheckCodeProjectExists(m => m.Name == project.Name, project.Id)) + dto.Validate(); + if (await CheckCodeProjectExists(m => m.Name == dto.Name, dto.Id)) { - return new OperationResult(OperationResultType.Error, $"名称为“{project.Name}”的项目信息已存在"); + return new OperationResult(OperationResultType.Error, $"名称为“{dto.Name}”的项目信息已存在"); } - int count = await ProjectRepository.UpdateAsync(project); + CodeProject existing = await ProjectRepository.GetAsync(dto.Id); + existing = dto.MapTo(existing); + int count = await ProjectRepository.UpdateAsync(existing); if (count > 0) { - names.Add(project.Name); + names.Add(dto.Name); } } @@ -125,5 +163,6 @@ namespace OSharp.CodeGeneration.Services ? new OperationResult(OperationResultType.Success, $"项目“{names.ExpandAndToString()}”删除成功") : OperationResult.NoChanged; } + } } diff --git a/src/OSharp.CodeGeneration/Services/DataService.CodeProperty.cs b/src/OSharp.CodeGeneration/Services/DataService.CodeProperty.cs index 9b778dce10e8201f85d246ba3ee544b40a4c6840..2643f53c4ff0f5bc5dff19fab3fdb83f7d3b4fc0 100644 --- a/src/OSharp.CodeGeneration/Services/DataService.CodeProperty.cs +++ b/src/OSharp.CodeGeneration/Services/DataService.CodeProperty.cs @@ -13,6 +13,7 @@ using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; +using OSharp.CodeGeneration.Services.Dtos; using OSharp.CodeGeneration.Services.Entities; using OSharp.Collections; using OSharp.Data; @@ -39,51 +40,56 @@ namespace OSharp.CodeGeneration.Services { return PropertyRepository.CheckExistsAsync(predicate, id); } - + /// /// 更新实体属性信息信息 /// - /// 包含更新信息的实体属性信息 + /// 包含更新信息的实体属性信息输入DTO /// 业务操作结果 - public async Task UpdateCodeProperties(params CodeProperty[] properties) + public async Task UpdateCodeProperties(params CodePropertyInputDto[] dtos) { List names = new List(); UnitOfWork.EnableTransaction(); - foreach (var property in properties) + foreach (var dto in dtos) { - property.Validate(); - CodeEntity entity = await EntityRepository.GetAsync(property.EntityId); + dto.Validate(); + CodeEntity entity = await EntityRepository.GetAsync(dto.EntityId); if (entity == null) { - return new OperationResult(OperationResultType.Error, $"编号为“{property.EntityId}”的实体信息不存在"); + return new OperationResult(OperationResultType.Error, $"编号为“{dto.EntityId}”的实体信息不存在"); } - if (await CheckCodePropertyExists(m => m.Name == property.Name && m.EntityId == property.EntityId, property.Id)) + if (await CheckCodePropertyExists(m => m.Name == dto.Name && m.EntityId == dto.EntityId, dto.Id)) { - return new OperationResult(OperationResultType.Error, $"实体“{entity.Name}”中名称为“{property.Name}”的属性信息已存在"); + return new OperationResult(OperationResultType.Error, $"实体“{entity.Name}”中名称为“{dto.Name}”的属性信息已存在"); } + if (dto.Order == 0) + { + dto.Order = PropertyRepository.Query(m => m.EntityId == entity.Id).Count() + 1; + } int count; - if (property.Id == default) + if (dto.Id == default) { + CodeProperty property = dto.MapTo(); count = await PropertyRepository.InsertAsync(property); } else { - CodeProperty existing = await PropertyRepository.GetAsync(property.Id); - existing = property.MapTo(existing); - count = await PropertyRepository.UpdateAsync(existing); + CodeProperty property = await PropertyRepository.GetAsync(dto.Id); + property = dto.MapTo(property); + count = await PropertyRepository.UpdateAsync(property); } if (count > 0) { - names.Add(property.Name); + names.Add(dto.Name); } } await UnitOfWork.CommitAsync(); return names.Count > 0 - ? new OperationResult(OperationResultType.Success, $"属性“{names.ExpandAndToString()}”更新成功") + ? new OperationResult(OperationResultType.Success, $"属性“{names.ExpandAndToString()}”保存成功") : OperationResult.NoChanged; } diff --git a/src/OSharp.CodeGeneration/Services/DataService.CodeSetting.cs b/src/OSharp.CodeGeneration/Services/DataService.CodeTemplate.cs similarity index 69% rename from src/OSharp.CodeGeneration/Services/DataService.CodeSetting.cs rename to src/OSharp.CodeGeneration/Services/DataService.CodeTemplate.cs index 62d09eebb493553a74f32bc3cfa045c52df191a7..806dde74acc44df72d8082cb57a450964ef72725 100644 --- a/src/OSharp.CodeGeneration/Services/DataService.CodeSetting.cs +++ b/src/OSharp.CodeGeneration/Services/DataService.CodeTemplate.cs @@ -13,6 +13,7 @@ using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; +using OSharp.CodeGeneration.Services.Dtos; using OSharp.CodeGeneration.Services.Entities; using OSharp.Collections; using OSharp.Data; @@ -28,7 +29,7 @@ namespace OSharp.CodeGeneration.Services /// /// 获取 代码设置信息查询数据集 /// - public IQueryable CodeSettings => SettingRepository.QueryAsNoTracking(); + public IQueryable CodeTemplates => TemplateRepository.QueryAsNoTracking(); /// /// 检查代码设置信息信息是否存在 @@ -36,43 +37,44 @@ namespace OSharp.CodeGeneration.Services /// 检查谓语表达式 /// 更新的代码设置信息编号 /// 代码设置信息是否存在 - public Task CheckCodeSettingExists(Expression> predicate, Guid id = default) + public Task CheckCodeTemplateExists(Expression> predicate, Guid id = default) { - return SettingRepository.CheckExistsAsync(predicate, id); + return TemplateRepository.CheckExistsAsync(predicate, id); } /// /// 更新代码设置信息信息 /// - /// 包含更新信息的代码设置信息 + /// 包含更新信息的代码设置信息 /// 业务操作结果 - public async Task UpdateCodeSettings(params CodeSetting[] entities) + public async Task UpdateCodeTemplates(params CodeTemplateInputDto[] dtos) { List names = new List(); UnitOfWork.EnableTransaction(); - foreach (var entity in entities) + foreach (var dto in dtos) { - entity.Validate(); - if (await CheckCodeSettingExists(m=>m.Name == entity.Name, entity.Id)) + dto.Validate(); + if (await CheckCodeTemplateExists(m=>m.Name == dto.Name, dto.Id)) { - return new OperationResult(OperationResultType.Error, $"名称为“{entity.Name}”的代码设置已存在"); + return new OperationResult(OperationResultType.Error, $"名称为“{dto.Name}”的代码设置已存在"); } int count; - if (entity.Id == default) + if (dto.Id == default) { - count = await SettingRepository.InsertAsync(entity); + CodeTemplate template = dto.MapTo(); + count = await TemplateRepository.InsertAsync(template); } else { - CodeSetting entity1 = await SettingRepository.GetAsync(entity.Id); - entity1 = entity.MapTo(entity1); - count = await SettingRepository.UpdateAsync(entity1); + CodeTemplate template = await TemplateRepository.GetAsync(dto.Id); + template = dto.MapTo(template); + count = await TemplateRepository.UpdateAsync(template); } if (count > 0) { - names.Add(entity.Name); + names.Add(dto.Name); } } @@ -87,13 +89,13 @@ namespace OSharp.CodeGeneration.Services /// /// 要删除的代码设置信息编号 /// 业务操作结果 - public async Task DeleteCodeSettings(params Guid[] ids) + public async Task DeleteCodeTemplates(params Guid[] ids) { List names = new List(); UnitOfWork.EnableTransaction(); foreach (var id in ids) { - var entity = await SettingRepository.GetAsync(id); + var entity = await TemplateRepository.GetAsync(id); if (entity == null) { continue; @@ -104,7 +106,7 @@ namespace OSharp.CodeGeneration.Services throw new OsharpException($"代码设置“{entity.Name}”是系统设置,不能删除"); } - int count = await SettingRepository.DeleteAsync(entity); + int count = await TemplateRepository.DeleteAsync(entity); if (count > 0) { names.Add(entity.Name); diff --git a/src/OSharp.CodeGeneration/Services/DataService.cs b/src/OSharp.CodeGeneration/Services/DataService.cs index 4060cd8da5363049d487fc2058c3d2a7a07b7c3a..43edae10b96129d8a5d72f11c362522b73d613bb 100644 --- a/src/OSharp.CodeGeneration/Services/DataService.cs +++ b/src/OSharp.CodeGeneration/Services/DataService.cs @@ -27,7 +27,7 @@ namespace OSharp.CodeGeneration.Services protected IRepository PropertyRepository => _serviceProvider.GetService>(); - protected IRepository SettingRepository => _serviceProvider.GetService>(); + protected IRepository TemplateRepository => _serviceProvider.GetService>(); protected IRepository ForeignRepository => _serviceProvider.GetService>(); } diff --git a/src/OSharp.CodeGeneration/Services/Dtos/CodeEntityInputDto.cs b/src/OSharp.CodeGeneration/Services/Dtos/CodeEntityInputDto.cs new file mode 100644 index 0000000000000000000000000000000000000000..1e5d2a2fb8eda6014c5a4e52e6c31f764f0eec10 --- /dev/null +++ b/src/OSharp.CodeGeneration/Services/Dtos/CodeEntityInputDto.cs @@ -0,0 +1,109 @@ +// ----------------------------------------------------------------------- +// +// Copyright (c) 2014-2021 OSharp. All rights reserved. +// +// http://www.osharp.org +// 郭明锋 +// 2021-04-10 21:54 +// ----------------------------------------------------------------------- + +using System; +using System.ComponentModel.DataAnnotations; + +using OSharp.CodeGeneration.Services.Entities; +using OSharp.Entity; +using OSharp.Mapping; + + +namespace OSharp.CodeGeneration.Services.Dtos +{ + [MapTo(typeof(CodeEntity))] + public class CodeEntityInputDto : IInputDto + { + /// + /// 获取或设置 编号 + /// + public Guid Id { get; set; } + + /// + /// 获取或设置 类型名称 + /// + [Required(), StringLength(200)] + public string Name { get; set; } + + /// + /// 获取或设置 类型显示名称 + /// + [Required(), StringLength(200)] + public string Display { get; set; } + + /// + /// 获取或设置 主键类型全名 + /// + [Required(), StringLength(500)] + public string PrimaryKeyTypeFullName { get; set; } + + /// + /// 获取或设置 是否可列表 + /// + public bool Listable { get; set; } + + /// + /// 获取或设置 是否可添加 + /// + public bool Addable { get; set; } + + /// + /// 获取或设置 是否可更新 + /// + public bool Updatable { get; set; } + + /// + /// 获取或设置 是否可删除 + /// + public bool Deletable { get; set; } + + /// + /// 获取或设置 是否数据权限控制 + /// + public bool IsDataAuth { get; set; } + + /// + /// 获取或设置 是否有创建时间 + /// + public bool HasCreatedTime { get; set; } + + /// + /// 获取或设置 是否有锁定 + /// + public bool HasLocked { get; set; } + + /// + /// 获取或设置 是否有软删除 + /// + public bool HasSoftDeleted { get; set; } + + /// + /// 获取或设置 是否有创建审计 + /// + public bool HasCreationAudited { get; set; } + + /// + /// 获取或设置 是否有更新审计 + /// + public bool HasUpdateAudited { get; set; } + + /// + /// 获取或设置 排序号 + /// + public int Order { get; set; } + + /// 获取或设置 是否锁定当前信息 + public bool IsLocked { get; set; } + + /// + /// 获取或设置 所属模块编号 + /// + public Guid ModuleId { get; set; } + } +} diff --git a/src/OSharp.CodeGeneration/Services/Dtos/CodeForeignInputDto.cs b/src/OSharp.CodeGeneration/Services/Dtos/CodeForeignInputDto.cs new file mode 100644 index 0000000000000000000000000000000000000000..7e1c5369657d2cbb300725a30341d9154c6de2e2 --- /dev/null +++ b/src/OSharp.CodeGeneration/Services/Dtos/CodeForeignInputDto.cs @@ -0,0 +1,68 @@ +// ----------------------------------------------------------------------- +// +// Copyright (c) 2014-2021 OSharp. All rights reserved. +// +// http://www.osharp.org +// 郭明锋 +// 2021-04-10 22:03 +// ----------------------------------------------------------------------- + +using System; + +using Microsoft.EntityFrameworkCore; + +using OSharp.CodeGeneration.Services.Entities; +using OSharp.Entity; +using OSharp.Mapping; + + +namespace OSharp.CodeGeneration.Services.Dtos +{ + [MapTo(typeof(CodeForeign))] + public class CodeForeignInputDto : IInputDto + { + /// 获取或设置 主键,唯一标识 + public Guid Id { get; set; } + + /// + /// 获取或设置 己方导航属性 + /// + public string SelfNavigation { get; set; } + + /// + /// 获取或设置 己方外键属性 + /// + public string SelfForeignKey { get; set; } + + /// + /// 获取或设置 对方实体 + /// + public string OtherEntity { get; set; } + + /// + /// 获取或设置 对方导航属性 + /// + public string OtherNavigation { get; set; } + + /// + /// 获取或设置 是否必须 + /// + public bool IsRequired { get; set; } + + /// + /// 获取或设置 关系数据删除行为 + /// + public DeleteBehavior? DeleteBehavior { get; set; } + + /// + /// 获取或设置 外键关系 + /// + public ForeignRelation ForeignRelation { get; set; } + + /// + /// 获取或设置 实体编号 + /// + public Guid EntityId { get; set; } + + } +} diff --git a/src/OSharp.CodeGeneration/Services/Dtos/CodeModuleInputDto.cs b/src/OSharp.CodeGeneration/Services/Dtos/CodeModuleInputDto.cs new file mode 100644 index 0000000000000000000000000000000000000000..8094d6282ab6f8376a545421120c23bf7502242d --- /dev/null +++ b/src/OSharp.CodeGeneration/Services/Dtos/CodeModuleInputDto.cs @@ -0,0 +1,51 @@ +// ----------------------------------------------------------------------- +// +// Copyright (c) 2014-2021 OSharp. All rights reserved. +// +// http://www.osharp.org +// 郭明锋 +// 2021-04-10 21:47 +// ----------------------------------------------------------------------- + +using System; +using System.ComponentModel.DataAnnotations; + +using OSharp.CodeGeneration.Services.Entities; +using OSharp.Entity; +using OSharp.Mapping; + + +namespace OSharp.CodeGeneration.Services.Dtos +{ + [MapTo(typeof(CodeModule))] + public class CodeModuleInputDto : IInputDto + { + /// 获取或设置 主键,唯一标识 + public Guid Id { get; set; } + + /// + /// 获取或设置 模块名称 + /// + [Required(), StringLength(200)] + public string Name { get; set; } + + /// + /// 获取或设置 模块显示名称 + /// + [Required(), StringLength(200)] + public string Display { get; set; } + + /// + /// 获取或设置 排序号 + /// + public int Order { get; set; } + + /// 获取或设置 是否锁定当前信息 + public bool IsLocked { get; set; } + + /// + /// 获取或设置 所属项目编号 + /// + public Guid ProjectId { get; set; } + } +} diff --git a/src/OSharp.CodeGeneration/Services/Dtos/CodeProjectInputDto.cs b/src/OSharp.CodeGeneration/Services/Dtos/CodeProjectInputDto.cs new file mode 100644 index 0000000000000000000000000000000000000000..3819ecde08546e10617b9f2aa558c4ada9cc0184 --- /dev/null +++ b/src/OSharp.CodeGeneration/Services/Dtos/CodeProjectInputDto.cs @@ -0,0 +1,62 @@ +// ----------------------------------------------------------------------- +// +// Copyright (c) 2014-2021 OSharp. All rights reserved. +// +// http://www.osharp.org +// 郭明锋 +// 2021-04-10 21:35 +// ----------------------------------------------------------------------- + +using System; +using System.ComponentModel.DataAnnotations; + +using OSharp.CodeGeneration.Services.Entities; +using OSharp.Entity; +using OSharp.Mapping; + + +namespace OSharp.CodeGeneration.Services.Dtos +{ + [MapTo(typeof(CodeProject))] + public class CodeProjectInputDto : IInputDto + { + /// 获取或设置 主键,唯一标识 + public Guid Id { get; set; } + + /// + /// 获取或设置 项目名称 + /// + [Required(), StringLength(200)] + public string Name { get; set; } + + /// + /// 获取或设置 项目命名空间前缀,通常形如“公司.项目” + /// + [Required(), StringLength(200)] + public string NamespacePrefix { get; set; } + + /// + /// 获取或设置 公司 + /// + [StringLength(200)] + public string Company { get; set; } + + /// + /// 获取或设置 站点地址 + /// + [StringLength(500)] + public string SiteUrl { get; set; } + + /// + /// 获取或设置 创建者 + /// + [StringLength(200)] + public string Creator { get; set; } + + /// + /// 获取或设置 Copyright + /// + [StringLength(500)] + public string Copyright { get; set; } + } +} diff --git a/src/OSharp.CodeGeneration/Services/Dtos/CodePropertyInputDto.cs b/src/OSharp.CodeGeneration/Services/Dtos/CodePropertyInputDto.cs new file mode 100644 index 0000000000000000000000000000000000000000..f12913cf304f5657975a32d12cfc2102bb82786a --- /dev/null +++ b/src/OSharp.CodeGeneration/Services/Dtos/CodePropertyInputDto.cs @@ -0,0 +1,137 @@ +// ----------------------------------------------------------------------- +// +// Copyright (c) 2014-2021 OSharp. All rights reserved. +// +// http://www.osharp.org +// 郭明锋 +// 2021-04-10 21:59 +// ----------------------------------------------------------------------- + +using System; +using System.ComponentModel.DataAnnotations; + +using OSharp.CodeGeneration.Services.Entities; +using OSharp.Entity; +using OSharp.Mapping; + + +namespace OSharp.CodeGeneration.Services.Dtos +{ + [MapTo(typeof(CodeProperty))] + public class CodePropertyInputDto : IInputDto + { + /// 获取或设置 主键,唯一标识 + public Guid Id { get; set; } + + /// + /// 获取或设置 属性名称 + /// + [Required(), StringLength(200)] + public string Name { get; set; } + + /// + /// 获取或设置 显示名称 + /// + [StringLength(200)] + public string Display { get; set; } + + /// + /// 获取或设置 属性类型名称 + /// + [Required(), StringLength(500)] + public string TypeName { get; set; } + + /// + /// 获取或设置 是否可更新 + /// + public bool Updatable { get; set; } + + /// + /// 获取或设置 是否可排序 + /// + public bool Sortable { get; set; } + + /// + /// 获取或设置 是否可筛选 + /// + public bool Filterable { get; set; } + + /// + /// 获取或设置 是否必须 + /// + public bool? IsRequired { get; set; } + + /// + /// 获取或设置 最小长度 + /// + public int? MinLength { get; set; } + + /// + /// 获取或设置 最大长度 + /// + public int? MaxLength { get; set; } + + /// + /// 获取或设置 是否值类型可空 + /// + public bool IsNullable { get; set; } + + /// + /// 获取或设置 是否只读 + /// + public bool IsReadonly { get; set; } + + /// + /// 获取或设置 是否虚属性 + /// + public bool IsVirtual { get; set; } + + /// + /// 获取或设置 是否外键 + /// + public bool IsForeignKey { get; set; } + + /// + /// 获取或设置 是否导航属性 + /// + public bool IsNavigation { get; set; } + + /// + /// 获取或设置 关联实体 + /// + public string RelateEntity { get; set; } + + /// + /// 获取或设置 数据权限标识 + /// + public string DataAuthFlag { get; set; } + + /// + /// 获取或设置 是否包含在输入Dto + /// + public bool IsInputDto { get; set; } = true; + + /// + /// 获取或设置 是否包含在输出Dto + /// + public bool IsOutputDto { get; set; } = true; + + /// + /// 获取或设置 默认值 + /// + public string DefaultValue { get; set; } + + /// + /// 获取或设置 排序号 + /// + public int Order { get; set; } + + /// 获取或设置 是否锁定当前信息 + public bool IsLocked { get; set; } + + /// + /// 获取或设置 实体编号 + /// + public Guid EntityId { get; set; } + } +} diff --git a/src/OSharp.CodeGeneration/Services/Dtos/CodeTemplateInputDto.cs b/src/OSharp.CodeGeneration/Services/Dtos/CodeTemplateInputDto.cs new file mode 100644 index 0000000000000000000000000000000000000000..1ab9972105eee5cf53705106f4e05ced25bc214d --- /dev/null +++ b/src/OSharp.CodeGeneration/Services/Dtos/CodeTemplateInputDto.cs @@ -0,0 +1,69 @@ +// ----------------------------------------------------------------------- +// +// Copyright (c) 2014-2021 OSharp. All rights reserved. +// +// http://www.osharp.org +// 郭明锋 +// 2021-04-10 22:07 +// ----------------------------------------------------------------------- + +using System; +using System.ComponentModel.DataAnnotations; + +using OSharp.CodeGeneration.Generates; +using OSharp.Entity; + + +namespace OSharp.CodeGeneration.Services.Dtos +{ + public class CodeTemplateInputDto : IInputDto + { + /// 获取或设置 主键,唯一标识 + public Guid Id { get; set; } + + /// + /// 获取或设置 配置名称 + /// + [Required, StringLength(200)] + public string Name { get; set; } + + /// + /// 获取或设置 元数据类型 + /// + public MetadataType MetadataType { get; set; } + + /// + /// 获取或设置 模板文件,默认内置,也可以由用户自定义加载 + /// + [Required, StringLength(500)] + public string TemplateFile { get; set; } + + /// + /// 获取或设置 排序 + /// + public int Order { get; set; } + + /// + /// 获取或设置 代码输出文件名格式 + /// + [Required, StringLength(300)] + public string OutputFileFormat { get; set; } + + /// + /// 获取或设置 是否只生成一次 + /// + public bool IsOnce { get; set; } + + /// + /// 获取或设置 系统类型 + /// + public bool IsSystem { get; set; } + + /// 获取或设置 是否锁定当前信息 + public bool IsLocked { get; set; } + + /// 获取或设置 创建时间 + public DateTime CreatedTime { get; set; } + + } +} diff --git a/src/OSharp.CodeGeneration/Services/Entities/CodeEntity.cs b/src/OSharp.CodeGeneration/Services/Entities/CodeEntity.cs index 73692a96a78ffcf0fc433f22f523703f14a6bbaf..c7608d5831e2b1cbac31a020576b3b8473f3c470 100644 --- a/src/OSharp.CodeGeneration/Services/Entities/CodeEntity.cs +++ b/src/OSharp.CodeGeneration/Services/Entities/CodeEntity.cs @@ -24,7 +24,7 @@ namespace OSharp.CodeGeneration.Services.Entities [Description("代码实体信息")] [TableNamePrefix("CodeGen")] [MapTo(typeof(CodeEntity))] - public class CodeEntity : EntityBase, ILockable + public class CodeEntity : EntityBase, ILockable, ICreatedTime { /// /// 获取或设置 类型名称 @@ -119,5 +119,10 @@ namespace OSharp.CodeGeneration.Services.Entities /// 获取或设置 实体的属性集合 /// public virtual ICollection Properties { get; set; } = new List(); + + /// + /// 获取或设置 外键集合 + /// + public virtual ICollection Foreigns { get; set; } = new List(); } } diff --git a/src/OSharp.CodeGeneration/Services/Entities/CodeForeignConfiguration.cs b/src/OSharp.CodeGeneration/Services/Entities/CodeForeignConfiguration.cs index 0d639357f6a0daef9f01894e41e90aa5103836f8..d0b10af340fc661bc25933f92f894827d025802a 100644 --- a/src/OSharp.CodeGeneration/Services/Entities/CodeForeignConfiguration.cs +++ b/src/OSharp.CodeGeneration/Services/Entities/CodeForeignConfiguration.cs @@ -22,7 +22,7 @@ namespace OSharp.CodeGeneration.Services.Entities /// 实体类型创建器 public override void Configure(EntityTypeBuilder builder) { - + builder.HasOne(m => m.Entity).WithMany(n => n.Foreigns).HasForeignKey(m => m.EntityId).IsRequired(); } } } diff --git a/src/OSharp.CodeGeneration/Services/Entities/CodeProject.cs b/src/OSharp.CodeGeneration/Services/Entities/CodeProject.cs index 6af2f140a97efd6e638a555c150493562a70bdcc..835a0366ef1b557bd73d28e003f558d2f1cfb849 100644 --- a/src/OSharp.CodeGeneration/Services/Entities/CodeProject.cs +++ b/src/OSharp.CodeGeneration/Services/Entities/CodeProject.cs @@ -14,6 +14,7 @@ using System.ComponentModel.DataAnnotations; using OSharp.Data; using OSharp.Entity; +using OSharp.Mapping; namespace OSharp.CodeGeneration.Services.Entities @@ -74,5 +75,9 @@ namespace OSharp.CodeGeneration.Services.Entities /// public virtual ICollection Modules { get; set; } = new List(); + /// + /// 获取或设置 项目模板集合 + /// + public virtual ICollection ProjectTemplates { get; set; } = new List(); } } diff --git a/src/OSharp.CodeGeneration/Services/Entities/CodeProjectTemplate.cs b/src/OSharp.CodeGeneration/Services/Entities/CodeProjectTemplate.cs new file mode 100644 index 0000000000000000000000000000000000000000..740e18e491e96b4c0c9a4a949c824a89fa2b3a0c --- /dev/null +++ b/src/OSharp.CodeGeneration/Services/Entities/CodeProjectTemplate.cs @@ -0,0 +1,49 @@ +// ----------------------------------------------------------------------- +// +// Copyright (c) 2014-2021 OSharp. All rights reserved. +// +// http://www.osharp.org +// 郭明锋 +// 2021-04-09 12:15 +// ----------------------------------------------------------------------- + +using System; +using System.ComponentModel; + +using OSharp.Entity; + + +namespace OSharp.CodeGeneration.Services.Entities +{ + /// + /// 实体类:项目模板配对 + /// + [Description("项目模板配对")] + [TableNamePrefix("CodeGen")] + public class CodeProjectTemplate : EntityBase, ILockable + { + /// 获取或设置 是否锁定当前信息 + public bool IsLocked { get; set; } + + /// + /// 获取或设置 项目编号 + /// + public Guid ProjectId { get; set; } + + /// + /// 获取或设置 项目信息 + /// + public virtual CodeProject Project { get; set; } + + /// + /// 获取或设置 模板编号 + /// + public Guid TemplateId { get; set; } + + /// + /// 获取或设置 模板信息 + /// + public virtual CodeTemplate Template { get; set; } + } + +} diff --git a/src/OSharp.CodeGeneration/Services/Entities/CodeProjectTemplateConfiguration.cs b/src/OSharp.CodeGeneration/Services/Entities/CodeProjectTemplateConfiguration.cs new file mode 100644 index 0000000000000000000000000000000000000000..803bf05a693148d374ff9a552e75648542d36f1e --- /dev/null +++ b/src/OSharp.CodeGeneration/Services/Entities/CodeProjectTemplateConfiguration.cs @@ -0,0 +1,29 @@ +// ----------------------------------------------------------------------- +// +// Copyright (c) 2014-2021 OSharp. All rights reserved. +// +// http://www.osharp.org +// 郭明锋 +// 2021-04-09 13:08 +// ----------------------------------------------------------------------- + +using System; + +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +using OSharp.Entity; + + +namespace OSharp.CodeGeneration.Services.Entities +{ + public class CodeProjectTemplateConfiguration : EntityTypeConfigurationBase + { + /// 重写以实现实体类型各个属性的数据库配置 + /// 实体类型创建器 + public override void Configure(EntityTypeBuilder builder) + { + builder.HasOne(m => m.Project).WithMany(n => n.ProjectTemplates).HasForeignKey(m => m.ProjectId).IsRequired(); + builder.HasOne(m => m.Template).WithMany(n => n.ProjectTemplates).HasForeignKey(m => m.TemplateId).IsRequired(); + } + } +} diff --git a/src/OSharp.CodeGeneration/Services/Entities/CodeProperty.cs b/src/OSharp.CodeGeneration/Services/Entities/CodeProperty.cs index 8937317ab12947030a1cb7c507d0c49e6e601cf4..1f8397d6d24f8fd0ee27a6e604616f648549028d 100644 --- a/src/OSharp.CodeGeneration/Services/Entities/CodeProperty.cs +++ b/src/OSharp.CodeGeneration/Services/Entities/CodeProperty.cs @@ -76,6 +76,11 @@ namespace OSharp.CodeGeneration.Services.Entities /// public bool IsNullable { get; set; } + /// + /// 获取或设置 是否只读 + /// + public bool IsReadonly { get; set; } + /// /// 获取或设置 是否虚属性 /// diff --git a/src/OSharp.CodeGeneration/Services/Entities/CodeSetting.cs b/src/OSharp.CodeGeneration/Services/Entities/CodeTemplate.cs similarity index 59% rename from src/OSharp.CodeGeneration/Services/Entities/CodeSetting.cs rename to src/OSharp.CodeGeneration/Services/Entities/CodeTemplate.cs index 815282c700df2d19388b9752f5bae45082e3817c..83bb8030a436e342d1b58f542be06635c2f3b5f2 100644 --- a/src/OSharp.CodeGeneration/Services/Entities/CodeSetting.cs +++ b/src/OSharp.CodeGeneration/Services/Entities/CodeTemplate.cs @@ -8,10 +8,12 @@ // ----------------------------------------------------------------------- using System; +using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using OSharp.CodeGeneration.Generates; +using OSharp.CodeGeneration.Templates; using OSharp.Entity; using OSharp.Extensions; @@ -19,11 +21,11 @@ using OSharp.Extensions; namespace OSharp.CodeGeneration.Services.Entities { /// - /// 实体类:代码设置 + /// 实体类:代码模板 /// - [Description("代码设置")] + [Description("代码模板")] [TableNamePrefix("CodeGen")] - public class CodeSetting : EntityBase, ILockable + public class CodeTemplate : EntityBase, ILockable, ICreatedTime { /// /// 获取或设置 配置名称 @@ -66,6 +68,55 @@ namespace OSharp.CodeGeneration.Services.Entities /// 获取或设置 是否锁定当前信息 public bool IsLocked { get; set; } + /// 获取或设置 创建时间 + public DateTime CreatedTime { get; set; } + + /// + /// 获取或设置 项目模板集合 + /// + public virtual ICollection ProjectTemplates { get; set; } = new List(); + + public Type GetInnerTemplateType() + { + switch (Name) + { + case "cs_实体类": + return typeof(cs_Entity); + case "cs_输入DTO类": + return typeof(cs_InputDto); + case "cs_输出DTO类": + return typeof(cs_OutputDto); + case "cs_模块Pack类": + return typeof(cs_ServicePack); + case "cs_模块服务契约接口": + return typeof(cs_ServiceContract); + case "cs_模块服务综合实现基类": + return typeof(cs_ServiceMainImplBase); + case "cs_模块服务综合实现类": + return typeof(cs_ServiceMainImpl); + case "cs_模块服务实体实现基类": + return typeof(cs_ServiceEntityImplBase); + case "cs_实体数据映射配置类": + return typeof(cs_EntityConfiguration); + case "cs_实体管理控制器基类": + return typeof(cs_AdminControllerBase); + case "cs_实体管理控制器类": + return typeof(cs_AdminController); + case "ng_Alain模块": + return typeof(ng_AlainModule); + case "ng_Alain模块路由": + return typeof(ng_AlainRouting); + case "ng_Alain模块组件": + return typeof(ng_AlainComponent); + case "ng_Alain模块组件Html": + return typeof(ng_AlainComponentHtml); + case "ng_Alain其他数据": + return typeof(ng_AlainOther); + default: + return null; + } + } + /// /// 获取项目代码输出文件名 /// @@ -99,5 +150,6 @@ namespace OSharp.CodeGeneration.Services.Entities .Replace("{Module.Name}", entity.Module.Name).Replace("{Entity.Name}", entity.Name); return fileName; } + } } diff --git a/src/OSharp.CodeGeneration/Services/Entities/CodeSettingConfiguration.cs b/src/OSharp.CodeGeneration/Services/Entities/CodeTemplateConfiguration.cs similarity index 81% rename from src/OSharp.CodeGeneration/Services/Entities/CodeSettingConfiguration.cs rename to src/OSharp.CodeGeneration/Services/Entities/CodeTemplateConfiguration.cs index a42c521adbf3761f188b9a5fb0e891c02785ddce..b9db2ab72f8eda52579d95f02fd62d07f5649864 100644 --- a/src/OSharp.CodeGeneration/Services/Entities/CodeSettingConfiguration.cs +++ b/src/OSharp.CodeGeneration/Services/Entities/CodeTemplateConfiguration.cs @@ -16,11 +16,11 @@ using OSharp.Entity; namespace OSharp.CodeGeneration.Services.Entities { - public class CodeSettingConfiguration : EntityTypeConfigurationBase + public class CodeTemplateConfiguration : EntityTypeConfigurationBase { /// 重写以实现实体类型各个属性的数据库配置 /// 实体类型创建器 - public override void Configure(EntityTypeBuilder builder) + public override void Configure(EntityTypeBuilder builder) { } } } diff --git a/src/OSharp.CodeGeneration/Services/IDataContract.cs b/src/OSharp.CodeGeneration/Services/IDataContract.cs index 45680284108702dab20a9e7f691ce5b71f2b85d9..225cfbb441288ab538bd2868c5934aadd836f2f2 100644 --- a/src/OSharp.CodeGeneration/Services/IDataContract.cs +++ b/src/OSharp.CodeGeneration/Services/IDataContract.cs @@ -12,6 +12,7 @@ using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; +using OSharp.CodeGeneration.Services.Dtos; using OSharp.CodeGeneration.Services.Entities; using OSharp.Data; @@ -38,19 +39,26 @@ namespace OSharp.CodeGeneration.Services /// 项目信息是否存在 Task CheckCodeProjectExists(Expression> predicate, Guid id = default); + /// + /// 获取指定条件的项目信息 + /// + /// 检查谓语表达式 + /// 项目信息集合 + CodeProject[] GetCodeProject(Expression>predicate); + /// /// 添加项目信息信息 /// - /// 要添加的项目信息 + /// 要添加的项目信息DTO信息 /// 业务操作结果 - Task CreateCodeProjects(params CodeProject[] projects); + Task CreateCodeProjects(params CodeProjectInputDto[] dtos); /// /// 更新项目信息信息 /// - /// 包含更新信息的项目信息 + /// 包含更新信息的项目信息DTO信息 /// 业务操作结果 - Task UpdateCodeProjects(params CodeProject[] projects); + Task UpdateCodeProjects(params CodeProjectInputDto[] dtos); /// /// 删除项目信息信息 @@ -60,7 +68,7 @@ namespace OSharp.CodeGeneration.Services Task DeleteCodeProjects(params Guid[] ids); #endregion - + #region 代码模块信息业务 /// @@ -75,30 +83,23 @@ namespace OSharp.CodeGeneration.Services /// 更新的代码模块信息编号 /// 代码模块信息是否存在 Task CheckCodeModuleExists(Expression> predicate, Guid id = default); - - /// - /// 添加代码模块信息信息 - /// - /// 要添加的代码模块信息 - /// 业务操作结果 - Task CreateCodeModules(params CodeModule[] modules); - + /// /// 更新代码模块信息信息 /// - /// 包含更新信息的代码模块信息 + /// 包含更新信息的代码模块信息DTO信息 /// 业务操作结果 - Task UpdateCodeModules(params CodeModule[] modules); - + Task UpdateCodeModules(params CodeModuleInputDto[] dtos); + /// /// 删除代码模块信息信息 /// /// 要删除的代码模块信息编号 /// 业务操作结果 Task DeleteCodeModules(params Guid[] ids); - + #endregion - + #region 代码实体信息业务 /// @@ -113,13 +114,13 @@ namespace OSharp.CodeGeneration.Services /// 更新的代码实体信息编号 /// 代码实体信息是否存在 Task CheckCodeEntityExists(Expression> predicate, Guid id = default); - + /// /// 更新代码实体信息信息 /// - /// 包含更新信息的代码实体信息 + /// 包含更新信息的代码实体信息DTO信息 /// 业务操作结果 - Task UpdateCodeEntities(params CodeEntity[] entities); + Task UpdateCodeEntities(params CodeEntityInputDto[] dtos); /// /// 删除代码实体信息信息 @@ -129,7 +130,7 @@ namespace OSharp.CodeGeneration.Services Task DeleteCodeEntities(params Guid[] ids); #endregion - + #region 实体属性信息业务 /// @@ -148,9 +149,9 @@ namespace OSharp.CodeGeneration.Services /// /// 更新实体属性信息信息 /// - /// 包含更新信息的实体属性信息 + /// 包含更新信息的实体属性信息输入DTO /// 业务操作结果 - Task UpdateCodeProperties(params CodeProperty[] properties); + Task UpdateCodeProperties(params CodePropertyInputDto[] dtos); /// /// 删除实体属性信息信息 @@ -175,14 +176,14 @@ namespace OSharp.CodeGeneration.Services /// 更新的实体外键信息编号 /// 实体外键信息是否存在 Task CheckCodeForeignExists(Expression> predicate, Guid id = default); - + /// /// 更新实体外键信息信息 /// - /// 包含更新信息的实体外键信息 + /// 包含更新信息的实体外键信息输入DTO /// 业务操作结果 - Task UpdateCodeForeigns(params CodeForeign[] foreigns); - + Task UpdateCodeForeigns(params CodeForeignInputDto[] dtos); + /// /// 删除实体外键信息信息 /// @@ -191,36 +192,35 @@ namespace OSharp.CodeGeneration.Services Task DeleteCodeForeigns(params Guid[] ids); #endregion - - - #region 代码设置信息业务 + + #region 代码模板信息业务 /// - /// 获取 代码设置信息查询数据集 + /// 获取 代码模板信息查询数据集 /// - IQueryable CodeSettings { get; } + IQueryable CodeTemplates { get; } /// - /// 检查代码设置信息信息是否存在 + /// 检查代码模板信息信息是否存在 /// /// 检查谓语表达式 - /// 更新的代码设置信息编号 - /// 代码设置信息是否存在 - Task CheckCodeSettingExists(Expression> predicate, Guid id = default); + /// 更新的代码模板信息编号 + /// 代码模板信息是否存在 + Task CheckCodeTemplateExists(Expression> predicate, Guid id = default); /// - /// 更新代码设置信息信息 + /// 更新代码模板信息信息 /// - /// 包含更新信息的代码设置信息 + /// 包含更新信息的代码模板信息 /// 业务操作结果 - Task UpdateCodeSettings(params CodeSetting[] settings); + Task UpdateCodeTemplates(params CodeTemplateInputDto[] settings); /// - /// 删除代码设置信息信息 + /// 删除代码模板信息信息 /// - /// 要删除的代码设置信息编号 + /// 要删除的代码模板信息编号 /// 业务操作结果 - Task DeleteCodeSettings(params Guid[] ids); + Task DeleteCodeTemplates(params Guid[] ids); #endregion diff --git a/src/OSharp.CodeGeneration/Services/Seeds/CodeEntitySeedDataInitializer.cs b/src/OSharp.CodeGeneration/Services/Seeds/CodeEntitySeedDataInitializer.cs new file mode 100644 index 0000000000000000000000000000000000000000..96a1a9b55643165f227b4bd960f1f41e9aa94938 --- /dev/null +++ b/src/OSharp.CodeGeneration/Services/Seeds/CodeEntitySeedDataInitializer.cs @@ -0,0 +1,74 @@ +// ----------------------------------------------------------------------- +// +// Copyright (c) 2014-2021 OSharp. All rights reserved. +// +// http://www.osharp.org +// 郭明锋 +// 2021-04-09 17:14 +// ----------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; + +using Microsoft.Extensions.DependencyInjection; + +using OSharp.CodeGeneration.Services.Entities; +using OSharp.Entity; + + +namespace OSharp.CodeGeneration.Services.Seeds +{ + public class CodeEntitySeedDataInitializer : SeedDataInitializerBase + { + /// + /// 初始化一个类型的新实例 + /// + public CodeEntitySeedDataInitializer(IServiceProvider rootProvider) + : base(rootProvider) + { } + + /// 获取 种子数据初始化的顺序 + public override int Order => 3; + + /// 重写以提供要初始化的种子数据 + /// + protected override CodeEntity[] SeedData(IServiceProvider provider) + { + IRepository repository = provider.GetRequiredService>(); + CodeModule module = repository.GetFirst(m => m.Name == "Identity"); + List entities = new List() + { + new CodeEntity(){Name = "User", Display = "用户", Order = 1, PrimaryKeyTypeFullName = "System.Int32", ModuleId = module.Id}, + new CodeEntity(){Name = "Role", Display = "角色", Order = 2, PrimaryKeyTypeFullName = "System.Int32", ModuleId = module.Id}, + new CodeEntity(){Name = "UserRole", Display = "用户角色", Order = 3, PrimaryKeyTypeFullName = "System.Int32", ModuleId = module.Id}, + }; + + module = repository.GetFirst(m => m.Name == "Auth"); + entities.AddRange(new List() + { + new CodeEntity(){Name = "Module", Display = "模块", Order = 1, PrimaryKeyTypeFullName = "System.Int32", ModuleId = module.Id}, + new CodeEntity(){Name = "Function", Display = "功能", Order = 2, PrimaryKeyTypeFullName = "System.Guid", ModuleId = module.Id}, + new CodeEntity(){Name = "EntityInfo", Display = "实体", Order = 3, PrimaryKeyTypeFullName = "System.Guid", ModuleId = module.Id}, + }); + + module = repository.GetFirst(m => m.Name == "Infos"); + entities.AddRange(new List() + { + new CodeEntity(){Name = "Article", Display = "文章", Order = 1, PrimaryKeyTypeFullName = "System.Int32", ModuleId = module.Id}, + new CodeEntity(){Name = "Message", Display = "站内信", Order = 2, PrimaryKeyTypeFullName = "System.Guid", ModuleId = module.Id} + }); + + return entities.ToArray(); + } + + /// 重写以提供判断某个实体是否存在的表达式 + /// 要判断的实体 + /// + protected override Expression> ExistingExpression(CodeEntity entity) + { + return m => m.Name == entity.Name && m.ModuleId == entity.ModuleId; + } + } +} diff --git a/src/OSharp.CodeGeneration/Services/Seeds/CodeModuleSeedDataInitializer.cs b/src/OSharp.CodeGeneration/Services/Seeds/CodeModuleSeedDataInitializer.cs new file mode 100644 index 0000000000000000000000000000000000000000..f06c8078ef4e32b2bc069bab86406c38ab7d179e --- /dev/null +++ b/src/OSharp.CodeGeneration/Services/Seeds/CodeModuleSeedDataInitializer.cs @@ -0,0 +1,56 @@ +// ----------------------------------------------------------------------- +// +// Copyright (c) 2014-2021 OSharp. All rights reserved. +// +// http://www.osharp.org +// 郭明锋 +// 2021-04-09 17:01 +// ----------------------------------------------------------------------- + +using System; +using System.Linq; +using System.Linq.Expressions; + +using Microsoft.Extensions.DependencyInjection; + +using OSharp.CodeGeneration.Services.Entities; +using OSharp.Entity; + + +namespace OSharp.CodeGeneration.Services.Seeds +{ + public class CodeModuleSeedDataInitializer : SeedDataInitializerBase + { + /// + /// 初始化一个类型的新实例 + /// + public CodeModuleSeedDataInitializer(IServiceProvider rootProvider) + : base(rootProvider) + { } + + /// 获取 种子数据初始化的顺序 + public override int Order => 2; + + /// 重写以提供要初始化的种子数据 + /// + protected override CodeModule[] SeedData(IServiceProvider provider) + { + IRepository repository = provider.GetRequiredService>(); + CodeProject project = repository.GetFirst(m => m.Name == "示例项目"); + return new[] + { + new CodeModule(){Name = "Identity", Display = "身份认证", Order = 1, ProjectId = project.Id}, + new CodeModule(){Name = "Auth", Display = "权限授权", Order = 2, ProjectId = project.Id}, + new CodeModule(){Name = "Infos", Display = "信息", Order = 3, ProjectId = project.Id}, + }; + } + + /// 重写以提供判断某个实体是否存在的表达式 + /// 要判断的实体 + /// + protected override Expression> ExistingExpression(CodeModule entity) + { + return m => m.Name == entity.Name && m.ProjectId == entity.ProjectId; + } + } +} diff --git a/src/OSharp.CodeGeneration/Services/Seeds/CodeProjectSeedDataInitializer.cs b/src/OSharp.CodeGeneration/Services/Seeds/CodeProjectSeedDataInitializer.cs new file mode 100644 index 0000000000000000000000000000000000000000..b29e7d9c7bbe2fceb9010c4566446e208a75c886 --- /dev/null +++ b/src/OSharp.CodeGeneration/Services/Seeds/CodeProjectSeedDataInitializer.cs @@ -0,0 +1,52 @@ +// ----------------------------------------------------------------------- +// +// Copyright (c) 2014-2021 OSharp. All rights reserved. +// +// http://www.osharp.org +// 郭明锋 +// 2021-04-09 16:56 +// ----------------------------------------------------------------------- + +using System; +using System.Linq.Expressions; + +using OSharp.CodeGeneration.Services.Entities; +using OSharp.Entity; + + +namespace OSharp.CodeGeneration.Services.Seeds +{ + public class CodeProjectSeedDataInitializer : SeedDataInitializerBase + { + /// + /// 初始化一个类型的新实例 + /// + public CodeProjectSeedDataInitializer(IServiceProvider rootProvider) + : base(rootProvider) + { } + + /// 获取 种子数据初始化的顺序 + public override int Order => 1; + + /// 重写以提供要初始化的种子数据 + /// + protected override CodeProject[] SeedData(IServiceProvider provider) + { + return new[] + { + new CodeProject() + { + Name = "示例项目", NamespacePrefix = "Liuliu.Demo", Company = "LiuliuSoft", SiteUrl = "https://www.osharp.org", Creator = "郭明锋", Copyright = "OSHARP.ORG@2021" + } + }; + } + + /// 重写以提供判断某个实体是否存在的表达式 + /// 要判断的实体 + /// + protected override Expression> ExistingExpression(CodeProject entity) + { + return m => m.Name == entity.Name; + } + } +} diff --git a/src/OSharp.CodeGeneration/Services/Seeds/CodePropertySeedDataInitializer.cs b/src/OSharp.CodeGeneration/Services/Seeds/CodePropertySeedDataInitializer.cs new file mode 100644 index 0000000000000000000000000000000000000000..f4ef90fc0f184e231150d0a9584db98be534c62b --- /dev/null +++ b/src/OSharp.CodeGeneration/Services/Seeds/CodePropertySeedDataInitializer.cs @@ -0,0 +1,61 @@ +// ----------------------------------------------------------------------- +// +// Copyright (c) 2014-2021 OSharp. All rights reserved. +// +// http://www.osharp.org +// 郭明锋 +// 2021-04-09 18:09 +// ----------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using System.Linq.Expressions; + +using Microsoft.Extensions.DependencyInjection; + +using OSharp.CodeGeneration.Services.Entities; +using OSharp.Entity; + + +namespace OSharp.CodeGeneration.Services.Seeds +{ + public class CodePropertySeedDataInitializer : SeedDataInitializerBase + { + /// + /// 初始化一个类型的新实例 + /// + public CodePropertySeedDataInitializer(IServiceProvider rootProvider) + : base(rootProvider) + { } + + /// 获取 种子数据初始化的顺序 + public override int Order => 4; + + /// 重写以提供要初始化的种子数据 + /// + protected override CodeProperty[] SeedData(IServiceProvider provider) + { + IRepository repository = provider.GetRequiredService>(); + CodeEntity entity = repository.GetFirst(m => m.Name == "User"); + List properties = new List() + { + new CodeProperty(){Name = "UserName", Display = "用户名", TypeName = "System.String", Order = 1, IsRequired = true, MaxLength = 200, EntityId = entity.Id}, + new CodeProperty(){Name = "NickName", Display = "用户昵称", TypeName = "System.String", Order = 2, IsRequired = true, MaxLength = 200, EntityId = entity.Id}, + new CodeProperty(){Name = "Email", Display = "邮箱", TypeName = "System.String", Order = 3, MaxLength = 200, EntityId = entity.Id}, + new CodeProperty(){Name = "EmailConfirmed", Display = "邮箱确认", TypeName = "System.Boolean", Order = 4, EntityId = entity.Id}, + new CodeProperty(){Name = "PhoneNumber", Display = "手机号", TypeName = "System.String", Order = 5, MaxLength = 50, EntityId = entity.Id}, + new CodeProperty(){Name = "PhoneNumberConfirmed", Display = "手机号确认", TypeName = "System.Boolean", Order = 6, EntityId = entity.Id}, + }; + + return properties.ToArray(); + } + + /// 重写以提供判断某个实体是否存在的表达式 + /// 要判断的实体 + /// + protected override Expression> ExistingExpression(CodeProperty entity) + { + return m => m.Name == entity.Name && m.EntityId == entity.EntityId; + } + } +} diff --git a/src/OSharp.CodeGeneration/Services/Seeds/CodeTemplateSeedDataInitializer.cs b/src/OSharp.CodeGeneration/Services/Seeds/CodeTemplateSeedDataInitializer.cs new file mode 100644 index 0000000000000000000000000000000000000000..abf41e27b62c41d9f979c2c3144b2dbf88ff141e --- /dev/null +++ b/src/OSharp.CodeGeneration/Services/Seeds/CodeTemplateSeedDataInitializer.cs @@ -0,0 +1,65 @@ +// ----------------------------------------------------------------------- +// +// Copyright (c) 2014-2021 OSharp. All rights reserved. +// +// http://www.osharp.org +// 郭明锋 +// 2021-04-09 16:02 +// ----------------------------------------------------------------------- + +using System; +using System.Linq.Expressions; + +using OSharp.CodeGeneration.Generates; +using OSharp.CodeGeneration.Services.Entities; +using OSharp.Entity; + + +namespace OSharp.CodeGeneration.Services.Seeds +{ + public class CodeTemplateSeedDataInitializer : SeedDataInitializerBase + { + /// + /// 初始化一个类型的新实例 + /// + public CodeTemplateSeedDataInitializer(IServiceProvider rootProvider) + : base(rootProvider) + { } + + /// 获取 种子数据初始化的顺序 + public override int Order => 1; + + /// 重写以提供要初始化的种子数据 + /// + protected override CodeTemplate[] SeedData(IServiceProvider provider) + { + return new[] + { + new CodeTemplate(){Name = "cs_实体类", MetadataType = MetadataType.Entity, TemplateFile = "内置", Order = 1, IsSystem = true, OutputFileFormat = "{Project.NamespacePrefix}.Core/{Module.Name}/Entities/{Entity.Name}.generated.cs"}, + new CodeTemplate(){Name = "cs_输入DTO类", MetadataType = MetadataType.Entity, TemplateFile = "内置", Order = 2, IsSystem = true, OutputFileFormat = "{Project.NamespacePrefix}.Core/{Module.Name}/Dtos/{Entity.Name}InputDto.generated.cs"}, + new CodeTemplate(){Name = "cs_输出DTO类", MetadataType = MetadataType.Entity, TemplateFile = "内置", Order = 3, IsSystem = true, OutputFileFormat = "{Project.NamespacePrefix}.Core/{Module.Name}/Dtos/{Entity.Name}OutputDto.generated.cs"}, + new CodeTemplate(){Name = "cs_模块Pack类", MetadataType = MetadataType.Module, TemplateFile = "内置", Order = 4, IsSystem = true, IsOnce = true, OutputFileFormat = "{Project.NamespacePrefix}.Core/{Module.Name}/{Module.Name}Pack.cs"}, + new CodeTemplate(){Name = "cs_模块服务契约接口", MetadataType = MetadataType.Module, TemplateFile = "内置", Order = 5, IsSystem = true, OutputFileFormat = "{Project.NamespacePrefix}.Core/{Module.Name}/I{Module.Name}Contract.generated.cs"}, + new CodeTemplate(){Name = "cs_模块服务综合实现基类", MetadataType = MetadataType.Module, TemplateFile = "内置", Order = 6, IsSystem = true, OutputFileFormat = "{Project.NamespacePrefix}.Core/{Module.Name}/{Module.Name}ServiceBase.generated.cs"}, + new CodeTemplate(){Name = "cs_模块服务综合实现类", MetadataType = MetadataType.Module, TemplateFile = "内置", Order = 7, IsSystem = true, IsOnce = true, OutputFileFormat = "{Project.NamespacePrefix}.Core/{Module.Name}/{Module.Name}Service.cs"}, + new CodeTemplate(){Name = "cs_模块服务实体实现基类", MetadataType = MetadataType.Entity, TemplateFile = "内置", Order = 8, IsSystem = true, OutputFileFormat = "{Project.NamespacePrefix}.Core/{Module.Name}/{Module.Name}ServiceBase.{Entity.Name}.generated.cs"}, + new CodeTemplate(){Name = "cs_实体数据映射配置类", MetadataType = MetadataType.Entity, TemplateFile = "内置", Order = 9, IsSystem = true, OutputFileFormat = "{Project.NamespacePrefix}.EntityConfiguration/{Module.Name}/{Entity.Name}Configuration.generated.cs"}, + new CodeTemplate(){Name = "cs_实体管理控制器基类", MetadataType = MetadataType.Entity, TemplateFile = "内置", Order = 10, IsSystem = true, OutputFileFormat = "{Project.NamespacePrefix}.Web/Areas/Admin/Controllers/{Module.Name}/{Entity.Name}ControllerBase.generated.cs"}, + new CodeTemplate(){Name = "cs_实体管理控制器类", MetadataType = MetadataType.Entity, TemplateFile = "内置", Order = 11, IsSystem = true, IsOnce = true, OutputFileFormat = "{Project.NamespacePrefix}.Web/Areas/Admin/Controllers/{Module.Name}/{Entity.Name}Controller.cs"}, + new CodeTemplate(){Name = "ng_Alain模块", MetadataType = MetadataType.Module, TemplateFile = "内置", Order = 12, IsSystem = true, IsOnce = true, OutputFileFormat = "ui/ng-alain/src/app/routes/{Module.Name:Lower}/{Module.Name:Lower}.module.ts"}, + new CodeTemplate(){Name = "ng_Alain模块路由", MetadataType = MetadataType.Module, TemplateFile = "内置", Order = 13, IsSystem = true, IsOnce = true, OutputFileFormat = "ui/ng-alain/src/app/routes/{Module.Name:Lower}/{Module.Name:Lower}.routing.ts"}, + new CodeTemplate(){Name = "ng_Alain模块组件", MetadataType = MetadataType.Entity, TemplateFile = "内置", Order = 14, IsSystem = true, IsOnce = true, OutputFileFormat = "ui/ng-alain/src/app/routes/{Module.Name:Lower}/{Entity.Name:Lower}/{Entity.Name:Lower}.component.ts"}, + new CodeTemplate(){Name = "ng_Alain模块组件Html", MetadataType = MetadataType.Entity, TemplateFile = "内置", Order = 15, IsSystem = true, IsOnce = true, OutputFileFormat = "ui/ng-alain/src/app/routes/{Module.Name:Lower}/{Entity.Name:Lower}/{Entity.Name:Lower}.component.html"}, + new CodeTemplate(){Name = "ng_Alain其他数据", MetadataType = MetadataType.Project, TemplateFile = "内置", Order = 15, IsSystem = true, OutputFileFormat = "ui/ng-alain/src/assets/osharp/other.generated"}, + }; + } + + /// 重写以提供判断某个实体是否存在的表达式 + /// 要判断的实体 + /// + protected override Expression> ExistingExpression(CodeTemplate entity) + { + return m => m.Name == entity.Name; + } + } +} diff --git a/src/OSharp.CodeGeneration/Templates/TestTemplate.cshtml b/src/OSharp.CodeGeneration/Templates/TestTemplate.cshtml deleted file mode 100644 index b7d804657d2c187646aaff4fd54143d330fc43ea..0000000000000000000000000000000000000000 --- a/src/OSharp.CodeGeneration/Templates/TestTemplate.cshtml +++ /dev/null @@ -1,17 +0,0 @@ -@inherits TemplateBase -@namespace OSharp.CodeGeneration.Templates - -@using System -@using System.Threading.Tasks -@using Microsoft.AspNetCore.Razor.Language.Intermediate -@using Microsoft.EntityFrameworkCore -@using MiniRazor -@using OSharp.Extensions; -@using OSharp.CodeGeneration.Services.Entities -@{ CodeModule module = Model; } -namespace @(module.Namespace) -{ - public particl interface I@(module.Name)Contract - { - } -} diff --git a/src/OSharp.CodeGeneration/Templates/cs_AdminController.cshtml b/src/OSharp.CodeGeneration/Templates/cs_AdminController.cshtml new file mode 100644 index 0000000000000000000000000000000000000000..0cc584402e5fb4fd62309f3e697e4a9063d8bbf6 --- /dev/null +++ b/src/OSharp.CodeGeneration/Templates/cs_AdminController.cshtml @@ -0,0 +1,46 @@ +@inherits MiniRazor.TemplateBase +@namespace OSharp.CodeGeneration.Templates +@using System; +@using OSharp.CodeGeneration.Services.Entities +@using OSharp.CodeGeneration.Utils +@using OSharp.Collections; +@using OSharp.Exceptions; +@using OSharp.Extensions; +@{ + CodeEntity entity = Model; + string keyType = TypeHelper.ToSingleTypeName(entity.PrimaryKeyTypeFullName); +}// ----------------------------------------------------------------------- +// +// 这个文件只生成一次,再次生成不会被覆盖。 +// 可以在此类进行继承重写来扩展基类 @(entity.Name)ControllerBase +// +// +// +// @entity.Module.Project.Copyright +// +// @entity.Module.Project.SiteUrl +// @entity.Module.Project.Creator +// ----------------------------------------------------------------------- + +using System; + +using OSharp.Filter; + +using @(entity.Module.Namespace); + + +namespace @(entity.Module.Project.NamespacePrefix).Web.Areas.Admin.Controllers +{ + /// + /// 管理控制器: @(entity.Display)信息 + /// + public class @(entity.Name)Controller : @(entity.Name)ControllerBase + { + /// + /// 初始化一个类型的新实例 + /// + public @(entity.Name)Controller(IServiceProvider provider) + : base(provider) + { } + } +} diff --git a/src/OSharp.CodeGeneration/Templates/cs_AdminControllerBase.cshtml b/src/OSharp.CodeGeneration/Templates/cs_AdminControllerBase.cshtml new file mode 100644 index 0000000000000000000000000000000000000000..3fe84190faa2feec52c9f076a7584a906045a660 --- /dev/null +++ b/src/OSharp.CodeGeneration/Templates/cs_AdminControllerBase.cshtml @@ -0,0 +1,170 @@ +@inherits MiniRazor.TemplateBase +@namespace OSharp.CodeGeneration.Templates +@using System; +@using System.Collections.Generic; +@using System.Linq; +@using OSharp.CodeGeneration.Services.Entities +@using OSharp.CodeGeneration.Utils +@using OSharp.Collections; +@using OSharp.Exceptions; +@using OSharp.Extensions; +@{ + CodeEntity entity = Model; + string keyType = TypeHelper.ToSingleTypeName(entity.PrimaryKeyTypeFullName); +}// ----------------------------------------------------------------------- +// +// 此代码由代码生成器生成。 +// 手动更改此文件可能导致应用程序出现意外的行为。 +// 如果重新生成代码,对此文件的任何修改都会丢失。 +// 如果需要扩展此类,可以遵守如下规则进行扩展: +// 1.横向扩展:如需给当前控制器添加API,请在控制器类型 @(entity.Name)Controller.cs 进行添加 +// 2.纵向扩展:如需要重写当前控制器的API实现,请在控制器类型 @(entity.Name)Controller.cs 进行继承重写 +// +// +// +// @entity.Module.Project.Copyright +// +// @entity.Module.Project.SiteUrl +// @entity.Module.Project.Creator +// ----------------------------------------------------------------------- + +using System; +using System.ComponentModel; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; + +using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.DependencyInjection; + +using OSharp.AspNetCore.Mvc; +using OSharp.AspNetCore.Mvc.Filters; +using OSharp.AspNetCore.UI; +using OSharp.Caching; +using OSharp.Authorization.Functions; +using OSharp.Authorization.Modules; +using OSharp.Data; +using OSharp.Entity; +using OSharp.Filter; +using OSharp.Security; + +using @(entity.Module.Namespace); +using @(entity.Module.Namespace).Dtos; +using @(entity.Module.Namespace).Entities; + + +namespace @(entity.Module.Project.NamespacePrefix).Web.Areas.Admin.Controllers +{ + /// + /// 管理控制器基类: @(entity.Display)信息 + /// + [ModuleInfo(Position = "@(entity.Module.Name)", PositionName = "@(entity.Module.Display)模块")] + [Description("管理-@(entity.Display)信息")] + public abstract class @(entity.Name)ControllerBase : AdminApiController + { + private readonly IServiceProvider _provider; + + /// <summary> + /// 初始化一个<see cref="@(entity.Name)Controller"/>类型的新实例 + /// </summary> + protected @(entity.Name)ControllerBase(IServiceProvider provider) + { + _provider = provider; + } + + /// + /// 获取或设置 数据过滤服务对象 + /// + protected IFilterService FilterService => _provider.GetRequiredService<IFilterService>(); + + /// + /// 获取或设置 @(entity.Module.Display)模块业务契约对象 + /// + protected I@(entity.Module.Name)Contract @(entity.Module.Name)Contract => _provider.GetRequiredService<I@(entity.Module.Name)Contract>(); +@if (entity.Listable) +{ + + /// <summary> + /// 读取@(entity.Display)列表信息 + /// </summary> + /// <param name="request">页请求信息</param> + /// <returns>JSON操作结果</returns> + [HttpPost] + [ModuleInfo] + [Description("读取")] + public virtual AjaxResult Read(PageRequest request) + { + Check.NotNull(request, nameof(request)); + + Expression<Func<@(entity.Name), bool>> predicate = FilterService.GetExpression<@(entity.Name)>(request.FilterGroup); + var page = @(entity.Module.Name)Contract.@(entity.Name.ToPlural()).ToPage<@(entity.Name), @(entity.Name)OutputDto>(predicate, request.PageCondition); + + return new AjaxResult("success", AjaxResultType.Success, page.ToPageData()); + } + +} +@if (entity.Addable) +{ + + /// <summary> + /// 新增@(entity.Display)信息 + /// </summary> + /// <param name="dtos">@(entity.Display)信息输入DTO</param> + /// <returns>JSON操作结果</returns> + [HttpPost] + [ModuleInfo] + [DependOnFunction(nameof(Read))] + [UnitOfWork] + [Description("新增")] + public virtual async Task<AjaxResult> Create(@(entity.Name)InputDto[] dtos) + { + Check.NotNull(dtos, nameof(dtos)); + OperationResult result = await @(entity.Module.Name)Contract.Create@(entity.Name.ToPlural())(dtos); + return result.ToAjaxResult(); + } + +} +@if (entity.Updatable) +{ + + /// <summary> + /// 更新@(entity.Display)信息 + /// </summary> + /// <param name="dtos">@(entity.Display)信息输入DTO</param> + /// <returns>JSON操作结果</returns> + [HttpPost] + [ModuleInfo] + [DependOnFunction(nameof(Read))] + [UnitOfWork] + [Description("更新")] + public virtual async Task<AjaxResult> Update(@(entity.Name)InputDto[] dtos) + { + Check.NotNull(dtos, nameof(dtos)); + OperationResult result = await @(entity.Module.Name)Contract.Update@(entity.Name.ToPlural())(dtos); + return result.ToAjaxResult(); + } + +} +@if (entity.Deletable) +{ + + /// <summary> + /// 删除@(entity.Display)信息 + /// </summary> + /// <param name="ids">@(entity.Display)信息编号</param> + /// <returns>JSON操作结果</returns> + [HttpPost] + [ModuleInfo] + [DependOnFunction(nameof(Read))] + [UnitOfWork] + [Description("删除")] + public virtual async Task<AjaxResult> Delete(@(keyType)[] ids) + { + Check.NotNull(ids, nameof(ids)); + OperationResult result = await @(entity.Module.Name)Contract.Delete@(entity.Name.ToPlural())(ids); + return result.ToAjaxResult(); + } + +} + } +} diff --git a/src/OSharp.CodeGeneration/Templates/cs_Entity.cshtml b/src/OSharp.CodeGeneration/Templates/cs_Entity.cshtml new file mode 100644 index 0000000000000000000000000000000000000000..a10a433f6ac28b003a62cb5a84357231941cc34d --- /dev/null +++ b/src/OSharp.CodeGeneration/Templates/cs_Entity.cshtml @@ -0,0 +1,147 @@ +@inherits MiniRazor.TemplateBase +@namespace OSharp.CodeGeneration.Templates +@using System; +@using System.Collections.Generic; +@using System.Linq; +@using OSharp.CodeGeneration.Services.Entities +@using OSharp.CodeGeneration.Utils +@using OSharp.Collections; +@using OSharp.Exceptions; +@using OSharp.Extensions; +@{ + CodeEntity entity = Model; + string keyType = TypeHelper.ToSingleTypeName(entity.PrimaryKeyTypeFullName); + List addNamespaces = entity.Properties.Where(m => m.RelateEntity != null).Select(m => TypeHelper.GetNamespace(m.RelateEntity)) + .Union(entity.Properties.Where(m => m.TypeName.Contains(".") && !m.TypeName.StartsWith("System.")).Select(m => TypeHelper.GetNamespace(m.TypeName))) + .Distinct().Where(m => m != entity.Module.Namespace + ".Entities").ToList(); +}//------------------------------------------------------------------------------ +// +// 此代码由代码生成器生成。 +// 手动更改此文件可能导致应用程序出现意外的行为。 +// 如果重新生成代码,对此文件的任何修改都会丢失。 +// 如果需要扩展此类:可遵守如下规则进行扩展: +// 1.横向扩展:如需添加额外的属性,可新建文件“@(entity.Name).cs”的分部类“public partial class @(entity.Name)”}添加属性 +// +// +// +// @entity.Module.Project.Copyright +// +// @entity.Module.Project.SiteUrl +// @entity.Module.Project.Creator +// ----------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +using OSharp.Entity; + +@foreach (var space in addNamespaces) +{ +using @(space); +} + +namespace @(entity.Module.Namespace).Entities +{ + /// <summary> + /// 实体类:@(entity.Display)信息 + /// </summary> + [Description("@(entity.Display)信息")] + [TableNamePrefix("@(entity.Module.Name)")] + public partial class @entity.Name : @(GetInterfaces(entity, keyType)) + { +@foreach (var prop in entity.Properties.OrderBy(m => m.IsForeignKey || m.IsNavigation)) +{ + /// <summary> + /// 获取或设置 @prop.Display + /// </summary> + [@GetAttributes(prop)] + public @GetProperty(prop) + + +} + } +} + +@functions +{ + + static string GetInterfaces(CodeEntity entity, string keyType) + { + List list = new List(); + + list.Add(string.Format("EntityBase<{0}>", keyType)); + list.AddIf("ILockable", entity.HasLocked); + list.AddIf("ISoftDeletable", entity.HasSoftDeleted); + list.AddIf("ICreationAudited", entity.HasCreationAudited); + list.AddIf("ICreatedTime", !entity.HasCreationAudited && entity.HasCreatedTime); + list.AddIf("IUpdateAudited", entity.HasUpdateAudited); + + return list.ExpandAndToString(", "); + } + + static string GetAttributes(CodeProperty prop) + { + Listlist = new List(); + list.Add(string.Format("DisplayName(\"{0}\")", prop.Display)); + if (prop.TypeName == "System.String") + { + if (prop.IsRequired != null && prop.IsRequired.Value) + { + list.Add("Required"); + } + if (prop.MaxLength > 0) + { + string min = prop.MinLength > -1 ? string.Format(", MinimumLength = {0}", prop.MinLength.Value) : ""; + list.Add(string.Format("StringLength({0}{1})", prop.MaxLength.Value, min)); + } + } + if (!string.IsNullOrEmpty(prop.DataAuthFlag)) + { + list.Add(prop.DataAuthFlag); + } + + return list.ExpandAndToString(", "); + } + + static string GetProperty(CodeProperty prop) + { + string propName = "{0}.{1}.{2}".FormatWith(prop.Entity.Module.Name, prop.Entity.Name, prop.Name); + Listlist = new List(); + + //导航属性,添加virtual + if (prop.IsNavigation) + { + list.Add("virtual"); + } + + //属性类型 + string propType = TypeHelper.ToSingleTypeName(prop.TypeName); + if (propType == "ICollection<>") + { + if (prop.RelateEntity.IsNullOrEmpty()) + { + throw new OsharpException("属性“{0}”类型为“ICollection<>”的导航属性,关联实体不能为空".FormatWith(propName)); + } + propType = string.Format("ICollection<{0}>".FormatWith(TypeHelper.ToSingleTypeName(prop.RelateEntity))); + } + //可空的值类型,添加?符号 + Type tmpType = Type.GetType(prop.TypeName); + if (prop.IsNullable && tmpType != null && tmpType.IsValueType) + { + propType += "?"; + } + list.Add(propType); + list.Add(prop.Name); + list.Add("{ get; set; }"); + + if (propType == "ICollection<>") + { + list.Add(string.Format("= new List<{0}>();", TypeHelper.ToSingleTypeName(prop.RelateEntity))); + } + + return list.ExpandAndToString(" "); + } + +} diff --git a/src/OSharp.CodeGeneration/Templates/cs_EntityConfiguration.cshtml b/src/OSharp.CodeGeneration/Templates/cs_EntityConfiguration.cshtml new file mode 100644 index 0000000000000000000000000000000000000000..e3f2d0709eb33d25c3f2a48ebeca63ff4a98f362 --- /dev/null +++ b/src/OSharp.CodeGeneration/Templates/cs_EntityConfiguration.cshtml @@ -0,0 +1,172 @@ +@inherits MiniRazor.TemplateBase +@namespace OSharp.CodeGeneration.Templates +@using System; +@using System.Collections.Generic +@using System.Linq +@using OSharp.CodeGeneration.Services.Entities +@using OSharp.CodeGeneration.Utils +@using OSharp.Collections; +@using OSharp.Exceptions; +@using OSharp.Extensions; +@{ + CodeEntity entity = Model; + string keyType = TypeHelper.ToSingleTypeName(entity.PrimaryKeyTypeFullName); + string[] spaces = entity.Properties.Where(m => m.RelateEntity != null).Select(m => TypeHelper.GetNamespace(m.RelateEntity)) + .Distinct().Where(m => m != entity.Module.Namespace + ".Entities").ToArray(); +}//------------------------------------------------------------------------------ +// +// 此代码由代码生成器生成。 +// 手动更改此文件可能导致应用程序出现意外的行为。 +// 如果重新生成代码,对此文件的任何修改都会丢失。 +// 如果需要扩展此类:可遵守如下规则进行扩展: +// 1.横向扩展:如需添加额外的映射,可新建文件“@(entity.Name)Configuration.cs”的分部类“public partial class @(entity.Name)Configuration”}实现分部方法 EntityConfigurationAppend 进行扩展 +// +// +// +// @entity.Module.Project.Copyright +// +// @entity.Module.Project.SiteUrl +// @entity.Module.Project.Creator +// ----------------------------------------------------------------------- + +using System; +using System.Collections.Generic; + +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +using OSharp.Entity; + +using @(entity.Module.Namespace).Entities; +@foreach (var space in spaces) +{ +using @(space); +} + + +namespace @(entity.Module.Project.NamespacePrefix).EntityConfiguration.@entity.Module.Name +{ + /// <summary> + /// 实体配置类:@(entity.Display)信息 + /// </summary> + public partial class @(entity.Name)Configuration : EntityTypeConfigurationBase<@(entity.Name), @(keyType)> + { + /// <summary> + /// 重写以实现实体类型各个属性的数据库配置 + /// </summary> + /// <param name="builder">实体类型创建器</param> + public override void Configure(EntityTypeBuilder<@entity.Name> builder) + { +@foreach (var foreign in entity.Foreigns) +{ + @GetForeign(foreign, entity) +} + + EntityConfigurationAppend(builder); + } + + /// + /// 额外的数据映射 + /// + partial void EntityConfigurationAppend(EntityTypeBuilder<@entity.Name> builder); + } +} + +@functions +{ + + + static string GetForeign(CodeForeign foreign, CodeEntity entity) + { + List list = new List(); + + list.Add("builder"); + list.Add(Relation(foreign, entity)); + list.Add(";"); + + return list.ExpandAndToString(""); + } + + private static string Relation(CodeForeign foreign, CodeEntity entity) + { + string line = string.Empty; + switch (foreign.ForeignRelation) + { + case ForeignRelation.OneToMany: + line += ".HasMany"; + break; + case ForeignRelation.ManyToOne: + line += ".HasOne"; + break; + case ForeignRelation.OneToOne: + line += ".HasOne"; + break; + case ForeignRelation.OwnsOne: + line += ".OwnsOne"; + break; + case ForeignRelation.OwnsMany: + line += ".OwnsMany"; + break; + default: + throw new ArgumentOutOfRangeException(); + } + + if (!string.IsNullOrEmpty(foreign.OtherEntity)) + { + line += string.Format("<{0}>", TypeHelper.ToSingleTypeName(foreign.OtherEntity)); + } + line += "("; + if (!string.IsNullOrEmpty(foreign.SelfNavigation)) + { + line += string.Format("m => m.{0}", foreign.SelfNavigation); + } + line += ")"; + switch (foreign.ForeignRelation) + { + case ForeignRelation.OneToMany: + line += ".WithOne("; + break; + case ForeignRelation.ManyToOne: + line += ".WithMany("; + break; + case ForeignRelation.OneToOne: + line += ".WithOne("; + break; + case ForeignRelation.OwnsOne: + break; + case ForeignRelation.OwnsMany: + break; + default: + throw new ArgumentOutOfRangeException(); + } + if (!new []{ForeignRelation.OwnsOne, ForeignRelation.OwnsMany}.Contains(foreign.ForeignRelation)) + { + if (!string.IsNullOrEmpty(foreign.OtherNavigation)) + { + line += string.Format("n => n.{0})", foreign.OtherNavigation); + } + else + { + line += ")"; + } + if (!string.IsNullOrEmpty(foreign.SelfForeignKey)) + { + line += ".HasForeignKey"; + if (foreign.ForeignRelation == ForeignRelation.OneToOne) + { + line += string.Format("<{0}>", TypeHelper.ToSingleTypeName(entity.Name)); + } + line += string.Format("(m => m.{0})", foreign.SelfForeignKey); + } + if (foreign.IsRequired) + { + line += ".IsRequired()"; + } + if (foreign.DeleteBehavior != null) + { + line += string.Format(".OnDelete(DeleteBehavior.{0})", foreign.DeleteBehavior.Value.ToString()); + } + } + return line; + } +} diff --git a/src/OSharp.CodeGeneration/Templates/cs_InputDto.cshtml b/src/OSharp.CodeGeneration/Templates/cs_InputDto.cshtml new file mode 100644 index 0000000000000000000000000000000000000000..95d4b1fa79ddf7f58be492b5245e3547c7e664ab --- /dev/null +++ b/src/OSharp.CodeGeneration/Templates/cs_InputDto.cshtml @@ -0,0 +1,106 @@ +@inherits MiniRazor.TemplateBase +@namespace OSharp.CodeGeneration.Templates +@using System; +@using System.Collections.Generic +@using System.Linq +@using OSharp.CodeGeneration.Services.Entities +@using OSharp.CodeGeneration.Utils +@using OSharp.Collections; +@using OSharp.Exceptions; +@using OSharp.Extensions; +@{ + CodeEntity entity = Model; + string keyType = TypeHelper.ToSingleTypeName(entity.PrimaryKeyTypeFullName); +}// ----------------------------------------------------------------------- +// +// 此代码由代码生成器生成。 +// 手动更改此文件可能导致应用程序出现意外的行为。 +// 如果重新生成代码,对此文件的任何修改都会丢失。 +// 如果需要扩展此类:可遵守如下规则进行扩展: +// 1.横向扩展:如需添加额外的属性,可新建文件“@(entity.Name)InputDto.cs”的分部类“public partial class @(entity.Name)InputDto”}添加属性 +// +// +// +// @entity.Module.Project.Copyright +// +// @entity.Module.Project.SiteUrl +// @entity.Module.Project.Creator +// ----------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +using OSharp.Entity; +using OSharp.Mapping; + +using @(entity.Module.Namespace).Entities; + + +namespace @(entity.Module.Namespace).Dtos +{ + /// <summary> + /// 输入DTO:@(entity.Display)信息 + /// </summary> + [MapTo(typeof(@(entity.Name)))] + [Description("@(entity.Display)信息")] + public partial class @(entity.Name)InputDto : IInputDto<@(keyType)> + { + /// <summary> + /// 获取或设置 编号 + /// </summary> + [DisplayName("编号")] + public @(keyType) Id { get; set; } + +@foreach (CodeProperty prop in entity.Properties.Where(m => m.IsInputDto)) +{ + /// <summary> + /// 获取或设置 @(prop.Display) + /// </summary> + [@GetAttributes(prop)] + public @GetPropString(prop) @prop.Name { get; set; } + + +} + } +} +@functions +{ + + private static string GetAttributes(CodeProperty prop) + { + Listlist = new List(); + list.Add(string.Format("DisplayName(\"{0}\")", prop.Display)); + if (prop.TypeName == "System.String") + { + if (prop.IsRequired.HasValue && prop.IsRequired.Value) + { + list.Add("Required"); + } + if (prop.MaxLength > 0) + { + string min = prop.MinLength > -1 ? string.Format(", MinimumLength = {0}", prop.MinLength.Value) : ""; + list.Add(string.Format("StringLength({0}{1})", prop.MaxLength.Value, min)); + } + } + return list.ExpandAndToString(", "); + } + + private static string GetPropString(CodeProperty prop) + { + Listlist = new List(); + + string propType = TypeHelper.ToSingleTypeName(prop.TypeName); + //可空的值类型,添加?符号 + Type tmpType = Type.GetType(prop.TypeName); + if (prop.IsNullable && tmpType != null && tmpType.IsValueType) + { + propType += "?"; + } + list.Add(propType); + + return list.ExpandAndToString(""); + } + +} diff --git a/src/OSharp.CodeGeneration/Templates/cs_OutputDto.cshtml b/src/OSharp.CodeGeneration/Templates/cs_OutputDto.cshtml new file mode 100644 index 0000000000000000000000000000000000000000..b3edb6edcedde09abb813e958e340906f9ffbdbe --- /dev/null +++ b/src/OSharp.CodeGeneration/Templates/cs_OutputDto.cshtml @@ -0,0 +1,148 @@ +@inherits MiniRazor.TemplateBase +@namespace OSharp.CodeGeneration.Templates +@using System; +@using System.Collections.Generic +@using System.Linq +@using OSharp.CodeGeneration.Services.Entities +@using OSharp.CodeGeneration.Utils +@using OSharp.Collections; +@using OSharp.Exceptions; +@using OSharp.Extensions; +@{ + CodeEntity entity = Model; + string keyType = TypeHelper.ToSingleTypeName(entity.PrimaryKeyTypeFullName); + List addNamespaces = entity.Properties.Where(m => m.IsOutputDto && m.RelateEntity != null).Select(m => m.RelateEntity) + .Union(entity.Properties.Where(m => m.IsOutputDto && m.TypeName.Contains(".") && !m.TypeName.StartsWith("System.")).Select(m => m.TypeName)) + .Select(m => TypeHelper.GetNamespace(m).Replace(".Entities", ".Dtos")).Distinct().Where(m => m != entity.Module.Namespace + ".Dtos").ToList(); + +}// ----------------------------------------------------------------------- +// +// 此代码由代码生成器生成。 +// 手动更改此文件可能导致应用程序出现意外的行为。 +// 如果重新生成代码,对此文件的任何修改都会丢失。 +// 如果需要扩展此类:可遵守如下规则进行扩展: +// 1.横向扩展:如需添加额外的属性,可新建文件“@(entity.Name)OutputDto.cs”的分部类“public partial class @(entity.Name)OutputDto”}添加属性 +// +// +// +// @entity.Module.Project.Copyright +// +// @entity.Module.Project.SiteUrl +// @entity.Module.Project.Creator +// ----------------------------------------------------------------------- + +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; + +using OSharp.Entity; +using OSharp.Mapping; + +using @(entity.Module.Namespace).Entities; +@foreach (var space in addNamespaces) +{ +using @(space); +} + +namespace @(entity.Module.Namespace).Dtos +{ + /// <summary> + /// 输入DTO:@(entity.Display)信息 + /// </summary> + [MapFrom(typeof(@(entity.Name)))] + [Description("@(entity.Display)信息")] + public partial class @(entity.Name)OutputDto : @(GetInterfaces(entity)) + { + /// + /// 初始化一个类型的新实例 + /// + public @(entity.Name)OutputDto() + { } + + /// + /// 初始化一个类型的新实例 + /// + public @(entity.Name)OutputDto(@(entity.Name) entity) + { + Id = entity.Id; + @(GetCtorString(entity.Properties.Where(m => m.IsOutputDto && !m.IsNavigation).ToArray())); + } + + /// <summary> + /// 获取或设置 编号 + /// </summary> + [DisplayName("编号")] + public @(keyType) Id { get; set; } + +@foreach (CodeProperty prop in entity.Properties.Where(m => m.IsOutputDto)) +{ + /// <summary> + /// 获取或设置 @(prop.Display) + /// </summary> + [DisplayName("@(prop.Display)")] + public @GetPropString(prop) @prop.Name { get; set; } + + +} +@if(entity.IsDataAuth) +{ + /// + /// 获取或设置 是否可更新的数据权限状态 + /// + public bool Updatable { get; set; } + + /// + /// 获取或设置 是否可删除的数据权限状态 + /// + public bool Deletable { get; set; } + + +} + } +} +@functions +{ + private static string GetInterfaces(CodeEntity entity) + { + Listlist = new List(); + list.Add("IOutputDto"); + if (entity.IsDataAuth) + { + list.Add("IDataAuthEnabled"); + } + return list.ExpandAndToString(", "); + } + + private static string GetPropString(CodeProperty prop) + { + Listlist = new List(); + if (!prop.IsNavigation) + { + string propType = TypeHelper.ToSingleTypeName(prop.TypeName); + //可空的值类型,添加?符号 + Type tmpType = Type.GetType(prop.TypeName); + if (prop.IsNullable && tmpType != null && tmpType.IsValueType) + { + propType += "?"; + } + list.Add(propType); + } + else + { + string output = TypeHelper.ToSingleTypeName(prop.RelateEntity) + "OutputDto"; + list.Add(prop.TypeName == "ICollection<>" ? string.Format("ICollection<{0}>", output) : output); + } + return list.ExpandAndToString(""); + } + + private static string GetCtorString(CodeProperty[] props) + { + Listlist = new List(); + foreach (CodeProperty prop in props) + { + list.Add(string.Format("{0} = entity.{0}", prop.Name)); + } + return list.ExpandAndToString(";\r\n "); + } +} diff --git a/src/OSharp.CodeGeneration/Templates/cs_ServiceContract.cshtml b/src/OSharp.CodeGeneration/Templates/cs_ServiceContract.cshtml new file mode 100644 index 0000000000000000000000000000000000000000..9bb7cde2ff5a4f18f9b2f704e6dbb14ce5938743 --- /dev/null +++ b/src/OSharp.CodeGeneration/Templates/cs_ServiceContract.cshtml @@ -0,0 +1,102 @@ +@inherits MiniRazor.TemplateBase +@namespace OSharp.CodeGeneration.Templates +@using System; +@using OSharp.CodeGeneration.Services.Entities +@using OSharp.CodeGeneration.Utils +@using OSharp.Collections; +@using OSharp.Exceptions; +@using OSharp.Extensions; +@{ + CodeModule module = Model; +}// ----------------------------------------------------------------------- +// +// 此代码由代码生成器生成。 +// 手动更改此文件可能导致应用程序出现意外的行为。 +// 如果重新生成代码,对此文件的任何修改都会丢失。 +// 如果需要扩展此类,可以遵守如下规则进行扩展: +// 1. 横向扩展:如需给当前模块添加方法接口,可新建文件“I@(module.Name)Contract.cs”的分部接口“public partial interface I@(module.Name)Contract”添加方法,并添加相应新的分部基类 abstract partial class @(module.Name)ServiceBase 实现新方法 +// +// +// +// @module.Project.Copyright +// +// @module.Project.SiteUrl +// @module.Project.Creator +// ----------------------------------------------------------------------- + +using System; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; + +using OSharp.Data; +using OSharp.Extensions; + +using @(module.Namespace).Dtos; +using @(module.Namespace).Entities; + + +namespace @(module.Namespace) +{ + /// + /// 业务契约接口:@(module.Display)模块 + /// + public partial interface I@(module.Name)Contract + { +@foreach (CodeEntity entity in module.Entities) +{ + string keyType = TypeHelper.ToSingleTypeName(entity.PrimaryKeyTypeFullName); + #region @(entity.Display)信息业务 + + /// <summary> + /// 获取 @(entity.Display)信息查询数据集 + /// </summary> + IQueryable<@(entity.Name)> @(entity.Name.ToPlural()) { get; } + + /// <summary> + /// 检查@(entity.Display)信息信息是否存在 + /// </summary> + /// <param name="predicate">检查谓语表达式</param> + /// <param name="id">更新的@(entity.Display)信息编号</param> + /// <returns>@(entity.Display)信息是否存在</returns> + Task<bool> Check@(entity.Name)Exists(Expression<Func<@(entity.Name), bool>> predicate, @keyType id = default(@(keyType))); + + @if (entity.Addable) { + + /// <summary> + /// 添加@(entity.Display)信息信息 + /// </summary> + /// <param name="dtos">要添加的@(entity.Display)信息DTO信息</param> + /// <returns>业务操作结果</returns> + Task<OperationResult> Create@(entity.Name.ToPlural())(params @(entity.Name)InputDto[] dtos); + + } + @if (entity.Updatable) + { + + /// <summary> + /// 更新@(entity.Display)信息信息 + /// </summary> + /// <param name="dtos">包含更新信息的@(entity.Display)信息DTO信息</param> + /// <returns>业务操作结果</returns> + Task<OperationResult> Update@(entity.Name.ToPlural())(params @(entity.Name)InputDto[] dtos); + + } + @if (entity.Deletable) + { + + /// <summary> + /// 删除@(entity.Display)信息信息 + /// </summary> + /// <param name="ids">要删除的@(entity.Display)信息编号</param> + /// <returns>业务操作结果</returns> + Task<OperationResult> Delete@(entity.Name.ToPlural())(params @(keyType)[] ids); + + } + + #endregion + + +} + } +} diff --git a/src/OSharp.CodeGeneration/Templates/cs_ServiceEntityImplBase.cshtml b/src/OSharp.CodeGeneration/Templates/cs_ServiceEntityImplBase.cshtml new file mode 100644 index 0000000000000000000000000000000000000000..912755a3c99b6a9bf7f036e0e2d8883eec725761 --- /dev/null +++ b/src/OSharp.CodeGeneration/Templates/cs_ServiceEntityImplBase.cshtml @@ -0,0 +1,111 @@ +@inherits MiniRazor.TemplateBase +@namespace OSharp.CodeGeneration.Templates +@using System; +@using OSharp.CodeGeneration.Services.Entities +@using OSharp.CodeGeneration.Utils +@using OSharp.Collections; +@using OSharp.Exceptions; +@using OSharp.Extensions; +@{ + CodeEntity entity = Model; + string keyType = TypeHelper.ToSingleTypeName(entity.PrimaryKeyTypeFullName); +}// ----------------------------------------------------------------------- +// +// 此代码由代码生成器生成。 +// 手动更改此文件可能导致应用程序出现意外的行为。 +// 如果重新生成代码,对此文件的任何修改都会丢失。 +// 如果需要扩展此类,可以遵守如下规则进行扩展: +// 1.横向扩展:如需给当前实体 @entity.Name 添加方法,可新建文件“@(entity.Module.Name)ServiceBase.@(entity.Name).cs”的分部类“public abstract partial class @(entity.Module.Name)ServiceBase”添加功能 +// 2.纵向扩展:如需要重写当前实体 @entity.Name 的业务实现,可新建文件“@(entity.Module.Name)Service.@(entity.Name).cs”的分部类“public partial class @(entity.Module.Name)Service”对现有方法进行方法重写实现 +// +// +// +// @entity.Module.Project.Copyright +// +// @entity.Module.Project.SiteUrl +// @entity.Module.Project.Creator +// ----------------------------------------------------------------------- + +using System; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; + +using OSharp.Data; +using OSharp.Dependency; +using OSharp.Extensions; +using OSharp.Mapping; + +using @(entity.Module.Namespace).Dtos; +using @(entity.Module.Namespace).Entities; + + +namespace @(entity.Module.Namespace) +{ + public abstract partial class @(entity.Module.Name)ServiceBase + { + /// <summary> + /// 获取 @(entity.Display)信息查询数据集 + /// </summary> + public IQueryable<@(entity.Name)> @(entity.Name.ToPlural()) + { + get { return @(entity.Name)Repository.QueryAsNoTracking(); } + } + + /// <summary> + /// 检查@(entity.Display)信息是否存在 + /// </summary> + /// <param name="predicate">检查谓语表达式</param> + /// <param name="id">更新的@(entity.Display)信息编号</param> + /// <returns>@(entity.Display)信息是否存在</returns> + public virtual Task<bool> Check@(entity.Name)Exists(Expression<Func<@(entity.Name), bool>> predicate, @(keyType) id = default(@(keyType))) + { + return @(entity.Name)Repository.CheckExistsAsync(predicate, id); + } +@if (entity.Addable) +{ + + /// <summary> + /// 添加@(entity.Display)信息 + /// </summary> + /// <param name="dtos">要添加的@(entity.Display)信息DTO信息</param> + /// <returns>业务操作结果</returns> + public virtual Task<OperationResult> Create@(entity.Name.ToPlural())(params @(entity.Name)InputDto[] dtos) + { + Check.Validate<@(entity.Name)InputDto, @(keyType)>(dtos, nameof(dtos)); + return @(entity.Name)Repository.InsertAsync(dtos); + } + +} +@if (entity.Updatable) +{ + + /// <summary> + /// 更新@(entity.Display)信息 + /// </summary> + /// <param name="dtos">包含更新信息的@(entity.Display)信息DTO信息</param> + /// <returns>业务操作结果</returns> + public virtual Task<OperationResult> Update@(entity.Name.ToPlural())(params @(entity.Name)InputDto[] dtos) + { + Check.Validate<@(entity.Name)InputDto, @(keyType)>(dtos, nameof(dtos)); + return @(entity.Name)Repository.UpdateAsync(dtos); + } + +} +@if (entity.Deletable) +{ + + /// <summary> + /// 删除@(entity.Display)信息 + /// </summary> + /// <param name="ids">要删除的@(entity.Display)信息编号</param> + /// <returns>业务操作结果</returns> + public virtual Task<OperationResult> Delete@(entity.Name.ToPlural())(params @(keyType)[] ids) + { + Check.NotNull(ids, nameof(ids)); + return @(entity.Name)Repository.DeleteAsync(ids); + } + +} + } +} diff --git a/src/OSharp.CodeGeneration/Templates/cs_ServiceMainImpl.cshtml b/src/OSharp.CodeGeneration/Templates/cs_ServiceMainImpl.cshtml new file mode 100644 index 0000000000000000000000000000000000000000..0be837dc2aa73ffb26b0f11f7050f4d127f6643e --- /dev/null +++ b/src/OSharp.CodeGeneration/Templates/cs_ServiceMainImpl.cshtml @@ -0,0 +1,41 @@ +@inherits MiniRazor.TemplateBase +@namespace OSharp.CodeGeneration.Templates +@using System; +@using OSharp.CodeGeneration.Services.Entities +@using OSharp.CodeGeneration.Utils +@using OSharp.Collections; +@using OSharp.Exceptions; +@using OSharp.Extensions; +@{ + CodeModule module = Model; +}// ----------------------------------------------------------------------- +// +// 这个文件只生成一次,再次生成不会被覆盖。 +// 可以在此类进行继承重写来扩展基类 @(module.Name)ServiceBase +// +// +// +// @module.Project.Copyright +// +// @module.Project.SiteUrl +// @module.Project.Creator +// ----------------------------------------------------------------------- + +using System; + + +namespace @(module.Namespace) +{ + /// <summary> + /// 业务实现基类:@(module.Display)模块 + /// </summary> + public partial class @(module.Name)Service : @(module.Name)ServiceBase + { + /// + /// 初始化一个<see cref="@(module.Name)Service"/>类型的新实例 + /// + public @(module.Name)Service(IServiceProvider provider) + : base(provider) + { } + } +} diff --git a/src/OSharp.CodeGeneration/Templates/cs_ServiceMainImplBase.cshtml b/src/OSharp.CodeGeneration/Templates/cs_ServiceMainImplBase.cshtml new file mode 100644 index 0000000000000000000000000000000000000000..fad5a34c5ff151bb21e6b15efed9f86fc492209e --- /dev/null +++ b/src/OSharp.CodeGeneration/Templates/cs_ServiceMainImplBase.cshtml @@ -0,0 +1,94 @@ +@inherits MiniRazor.TemplateBase +@namespace OSharp.CodeGeneration.Templates +@using System; +@using OSharp.CodeGeneration.Services.Entities +@using OSharp.CodeGeneration.Utils +@using OSharp.Collections; +@using OSharp.Exceptions; +@using OSharp.Extensions; +@{ + CodeModule module = Model; +}// ----------------------------------------------------------------------- +// +// 此代码由代码生成器生成。 +// 手动更改此文件可能导致应用程序出现意外的行为。 +// 如果重新生成代码,对此文件的任何修改都会丢失。 +// 如果需要扩展此类,请在控制器类型 @(module.Name)Service 进行继承重写 +// +// +// +// @module.Project.Copyright +// +// @module.Project.SiteUrl +// @module.Project.Creator +// ----------------------------------------------------------------------- + +using System; +using System.Linq; +using System.Threading.Tasks; + +using OSharp.Core.Systems; +using OSharp.Data; +using OSharp.Entity; +using OSharp.EventBuses; +using OSharp.Extensions; +using OSharp.Identity; + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; + +using @(module.Namespace).Dtos; +using @(module.Namespace).Entities; + + +namespace @(module.Namespace) +{ + /// <summary> + /// 业务实现基类:@(module.Display)模块 + /// </summary> + public abstract partial class @(module.Name)ServiceBase : I@(module.Name)Contract + { + /// <summary> + /// 初始化一个<see cref="@(module.Name)Service"/>类型的新实例 + /// </summary> + protected @(module.Name)ServiceBase(IServiceProvider provider) + { + ServiceProvider = provider; + Logger = provider.GetLogger(GetType()); + } + + #region 属性 + + /// + /// 获取 服务提供者对象 + /// + protected IServiceProvider ServiceProvider { get; } + + /// + /// 获取 日志对象 + /// + protected ILogger Logger { get; } + +@foreach (CodeEntity entity in module.Entities) +{ + string keyType = TypeHelper.ToSingleTypeName(entity.PrimaryKeyTypeFullName); + /// <summary> + /// 获取 @(entity.Display)信息仓储对象 + /// </summary> + protected IRepository<@(entity.Name), @(keyType)> @(entity.Name)Repository => ServiceProvider.GetRequiredService<IRepository<@(entity.Name), @(keyType)>>(); + + +} + /// <summary> + /// 获取 事件总线 + /// </summary> + protected IEventBus EventBus => ServiceProvider.GetService<IEventBus>(); + + /// <summary> + /// 获取 设置存储对象 + /// </summary> + protected IKeyValueStore KeyValueStore => ServiceProvider.GetService<IKeyValueStore>(); + + #endregion + } +} diff --git a/src/OSharp.CodeGeneration/Templates/cs_ServicePack.cshtml b/src/OSharp.CodeGeneration/Templates/cs_ServicePack.cshtml new file mode 100644 index 0000000000000000000000000000000000000000..b220dcd6030b5e22a7614cb80792d3e147b43f55 --- /dev/null +++ b/src/OSharp.CodeGeneration/Templates/cs_ServicePack.cshtml @@ -0,0 +1,60 @@ +@inherits MiniRazor.TemplateBase +@namespace OSharp.CodeGeneration.Templates +@using System; +@using OSharp.CodeGeneration.Services.Entities +@using OSharp.CodeGeneration.Utils +@using OSharp.Collections; +@using OSharp.Exceptions; +@using OSharp.Extensions; +@{ + CodeModule module = Model; +}// ----------------------------------------------------------------------- +// +// 这个文件只生成一次,再次生成不会被覆盖。 +// 可以在此类的AddServices方法给“@(module.Name)”模块添加自定义服务配对,或者在UsePack方法进行模块初始化 +// +// +// +// @module.Project.Copyright +// +// @module.Project.SiteUrl +// @module.Project.Creator +// ----------------------------------------------------------------------- + +using System; +using System.ComponentModel; + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +using OSharp.Core.Packs; + + +namespace @(module.Namespace) +{ + /// <summary> + /// @(module.Display)模块 + /// </summary> + [Description("@(module.Display)模块")] + public class @(module.Name)Pack : OsharpPack + { + /// <summary>将模块服务添加到依赖注入服务容器中</summary> + /// <param name="services">依赖注入服务容器</param> + /// <returns></returns> + public override IServiceCollection AddServices(IServiceCollection services) + { + services.TryAddScoped<I@(module.Name)Contract, @(module.Name)Service>(); + + return services; + } + + /// <summary> + /// 应用模块服务 + /// </summary> + /// <param name="provider">服务提供者</param> + public override void UsePack(IServiceProvider provider) + { + base.UsePack(provider); + } + } +} diff --git a/src/OSharp.CodeGeneration/Templates/ng_AlainComponent.cshtml b/src/OSharp.CodeGeneration/Templates/ng_AlainComponent.cshtml new file mode 100644 index 0000000000000000000000000000000000000000..f771a945b7fada33bc259007d8398f21eedae7bb --- /dev/null +++ b/src/OSharp.CodeGeneration/Templates/ng_AlainComponent.cshtml @@ -0,0 +1,171 @@ +@inherits MiniRazor.TemplateBase +@namespace OSharp.CodeGeneration.Templates +@using System; +@using System.Collections.Generic; +@using System.Linq; +@using OSharp.CodeGeneration.Services.Entities +@using OSharp.CodeGeneration.Utils +@using OSharp.Collections; +@using OSharp.Exceptions; +@using OSharp.Extensions; +@{ + CodeEntity entity = Model; + string keyType = TypeHelper.ToSingleTypeName(entity.PrimaryKeyTypeFullName); + string lowerName = entity.Name.UpperToLowerAndSplit(); +}// ------------------------------------------------------------------------------ +// +// 这个文件只生成一次,再次生成不会被覆盖。 +// +// +// +// @entity.Module.Project.Copyright +// +// @entity.Module.Project.SiteUrl +// @entity.Module.Project.Creator +// ----------------------------------------------------------------------- + +import { Component, OnInit, Injector } from '@@angular/core'; +import { SFUISchema, SFSchema } from '@@delon/form'; +import { OsharpSTColumn } from '@@shared/osharp/services/alain.types'; +import { STComponentBase } from '@@shared/osharp/components/st-component-base'; + +@@Component({ + selector: 'app-@(lowerName)', + templateUrl: './@(lowerName).component.html', + styles: [] +}) +export class @(entity.Name)Component extends STComponentBase implements OnInit { + + constructor(injector: Injector) { + super(injector); + this.moduleName = '@(entity.Name.LowerFirstChar())'; + } + + ngOnInit() { + super.InitBase(); + } + + protected GetSTColumns(): OsharpSTColumn[] { + let columns: OsharpSTColumn[] = [ + { + title: '操作', fixed: 'left', width: 65, buttons: [{ + text: '操作', children: [ +@if (entity.Updatable) +{ + string line = string.Empty; + if (entity.IsDataAuth) + { + line += "iif: row => row.Updatable, "; + } + { text: '编辑', icon: 'edit', acl: 'Root.Admin.@(entity.Module.Name).@(entity.Name).Update', @(line)click: row => this.edit(row) }, + +} +@if (entity.Deletable) +{ + string line = string.Empty; + if (entity.IsDataAuth) + { + line += "iif: row => row.Deletable, "; + } + { text: '删除', icon: 'delete', type: 'del', acl: 'Root.Admin.@(entity.Module.Name).@(entity.Name).Delete', @(line)click: row => this.delete(row) }, + +} + ] + }] + }, + @GetIdColumn(entity) +@foreach (var prop in entity.Properties.Where(m => m.IsOutputDto)) +{ + { @(GetColumnProps(prop)) }, + +} + ]; + return columns; + } +@{ + CodeProperty[] requiredProps = entity.Properties.Where(m => m.IsRequired.GetValueOrDefault(false)).ToArray(); + if (requiredProps.Length > 0) + { + protected GetSFSchema(): SFSchema { + let schema: SFSchema = { + properties: this.ColumnsToSchemas(this.columns), + required: [@(requiredProps.Select(m => string.Format("'{0}'", m.Name)).ExpandAndToString(", "))] + }; + return schema; + } + + + } +} + protected GetSFUISchema(): SFUISchema { + let ui: SFUISchema = { + @(GetSFUISchemas(entity.Properties.ToArray())) + }; + return ui; + } +} + +@functions +{ + + static string GetIdColumn(CodeEntity entity) + { + string ftype = new[] { typeof(string).FullName, typeof(Guid).FullName }.Contains(entity.PrimaryKeyTypeFullName) ? "string" : "number"; + string line = "{ title: '编号', index: 'Id', sort: true, readOnly: true, editable: true, filterable: true, ftype: '" + ftype + "' },"; + return line; + } + + static string GetColumnProps(CodeProperty prop) + { + Listlist = new List(); + list.Add("title: '{0}'".FormatWith(prop.Display)); + list.Add("index: '{0}'".FormatWith(prop.Name)); + list.AddIf("readOnly: true", prop.IsReadonly); + list.AddIf("sort: true", prop.Sortable); + list.AddIf("editable: true", prop.Updatable); + list.AddIf("filterable: true", prop.Filterable); + list.AddRange(GetColumnType(prop)); + + return list.ExpandAndToString(", "); + } + + static string[] GetColumnType(CodeProperty prop) + { + Listlist = new List(); + switch (prop.TypeName) + { + case "System.String": + case "System.Guid": + list.Add("ftype: 'string'"); + break; + case "System.Int32": + case "System.Int64": + case "System.Double": + list.Add("type: 'number'"); + break; + case "System.Boolean": + list.Add("type: 'yn'"); + break; + case "System.DateTime": + list.Add("type: 'date'"); + break; + default: + list.Add("ftype: 'string'"); + break; + } + + return list.ToArray(); + } + + static string GetSFUISchemas(CodeProperty[] props) + { + Listlist = new List(); + list.Add("'*': { spanLabelFixed: 100, grid: { span: 12 } }"); + foreach (CodeProperty prop in props.Where(m => m.TypeName == "System.String")) + { + list.Add(string.Format("${0}: {{ grid: {{ span: 24 }} }}", prop.Name)); + } + + return list.ExpandAndToString(",\r\n "); + } +} diff --git a/src/OSharp.CodeGeneration/Templates/ng_AlainComponentHtml.cshtml b/src/OSharp.CodeGeneration/Templates/ng_AlainComponentHtml.cshtml new file mode 100644 index 0000000000000000000000000000000000000000..50a2dc5be66487edf9d772f801a5975b93235081 --- /dev/null +++ b/src/OSharp.CodeGeneration/Templates/ng_AlainComponentHtml.cshtml @@ -0,0 +1,39 @@ +@inherits MiniRazor.TemplateBase +@namespace OSharp.CodeGeneration.Templates +@using System; +@using System.Collections.Generic; +@using System.Linq; +@using OSharp.CodeGeneration.Services.Entities +@using OSharp.CodeGeneration.Utils +@using OSharp.Collections; +@using OSharp.Exceptions; +@using OSharp.Extensions; +@{ + CodeEntity entity = Model; + string keyType = TypeHelper.ToSingleTypeName(entity.PrimaryKeyTypeFullName); + string lowerName = entity.Name.UpperToLowerAndSplit(); +} + + + + + 刷新 +@if (entity.Addable) +{ + 新增 + +} + + + + + + + + + + diff --git a/src/OSharp.CodeGeneration/Templates/ng_AlainModule.cshtml b/src/OSharp.CodeGeneration/Templates/ng_AlainModule.cshtml new file mode 100644 index 0000000000000000000000000000000000000000..90a187409673d68b0f40b77153098665af4d73c6 --- /dev/null +++ b/src/OSharp.CodeGeneration/Templates/ng_AlainModule.cshtml @@ -0,0 +1,45 @@ +@inherits MiniRazor.TemplateBase +@namespace OSharp.CodeGeneration.Templates +@using System; +@using System.Linq; +@using OSharp.CodeGeneration.Services.Entities +@using OSharp.CodeGeneration.Utils +@using OSharp.Collections; +@using OSharp.Exceptions; +@using OSharp.Extensions; +@{ + CodeModule module = Model; +}// ----------------------------------------------------------------------- +// +// 这个文件只生成一次,再次生成不会被覆盖。 +// +// +// +// @module.Project.Copyright +// +// @module.Project.SiteUrl +// @module.Project.Creator +// ----------------------------------------------------------------------- + +import { NgModule } from '@@angular/core'; +import { CommonModule } from '@@angular/common'; +import { SharedModule } from '@@shared'; +import { @(module.Name)RoutingModule } from './@(module.Name.UpperToLowerAndSplit()).routing'; +@foreach (CodeEntity entity in module.Entities.Where(m => m.Listable)) +{ + var lowerName = entity.Name.UpperToLowerAndSplit(); +import { @(entity.Name)Component } from './@(lowerName)/@(lowerName).component'; + +} + +@@NgModule({ + imports: [CommonModule, SharedModule, @(module.Name)RoutingModule], + declarations: [ +@foreach (var entity in module.Entities.Where(m => m.Listable)) +{ + @(entity.Name)Component, + +} + ] +}) +export class @(module.Name)Module { } diff --git a/src/OSharp.CodeGeneration/Templates/ng_AlainOther.cshtml b/src/OSharp.CodeGeneration/Templates/ng_AlainOther.cshtml new file mode 100644 index 0000000000000000000000000000000000000000..0ae94cb55105d93b70ae098341d31181d4520110 --- /dev/null +++ b/src/OSharp.CodeGeneration/Templates/ng_AlainOther.cshtml @@ -0,0 +1,86 @@ +@inherits MiniRazor.TemplateBase +@namespace OSharp.CodeGeneration.Templates +@using System; +@using System.Collections.Generic +@using System.Linq; +@using OSharp.CodeGeneration.Services.Entities +@using OSharp.CodeGeneration.Utils +@using OSharp.Collections; +@using OSharp.Exceptions; +@using OSharp.Extensions; +@{ + CodeProject project = Model; +} +/* +各模块路由: +@foreach (var module in project.Modules) +{ + string name = module.Name.UpperToLowerAndSplit(); + { path: '@(name)', loadChildren: () => import('./@(name)/@(name).module').then(m => m.@(module.Name)Module), canActivateChild: [ACLGuard], data: { guard: 'Root.Admin.@(module.Name)' } }, + +} + +各模块组件路由: +@foreach (var module in project.Modules) +{ +@module.Display 模块组件路由数据 +@GetComponentRouters(module) + +} + +各模块菜单数据: +@foreach (var module in project.Modules) +{ +@module.Display 模块菜单数据 +@GetMenu(module) + +} +*/ +@functions +{ + + static string GetComponentRouters(CodeModule module) + { + Listlist = new List(); + foreach (var entity in module.Entities.Where(m=>m.Listable)) + { + list.Add(string.Format("{{ path: '{0}', component: {1}Component, canActivate: [ACLGuard], data: {{ title: '{2}管理', reuse: true, guard: 'Root.Admin.{3}.{1}.Read' }} }},\r\n", entity.Name.UpperToLowerAndSplit(), entity.Name, entity.Display, module.Name)); + } + return list.ExpandAndToString(""); + } + + static string GetMenu(CodeModule module) + { + Listlist = new List(); + list.Add("{\r\n"); + list.Add(string.Format(" \"text\": \"{0}模块\",\r\n", module.Display)); + list.Add( " \"group\": \"true\",\r\n"); + list.Add( " \"icon\": \"anticon-border\",\r\n"); + list.Add(string.Format(" \"acl\": \"Root.Admin.{0}\",\r\n", module.Name)); + string children = " \"children\": ["; + ListchildList = new List(); + foreach (var entity in module.Entities.Where(m => m.Listable)) + { + childList.Add(GetMenu(entity)); + } + if (childList.Count > 0) + { + children += childList.ExpandAndToString(", "); + } + children += "]\r\n"; + list.Add(children); + list.Add("}"); + return list.ExpandAndToString(""); + } + + static string GetMenu(CodeEntity entity) + { + Listlist = new List(); + list.Add("{\r\n"); + list.Add(string.Format(" \"text\": \"{0}管理\",\r\n", entity.Display)); + list.Add(string.Format(" \"link\": \"/{0}/{1}\",\r\n", entity.Module.Name.UpperToLowerAndSplit(), entity.Name.UpperToLowerAndSplit())); + list.Add(string.Format(" \"acl\": \"Root.Admin.{0}.{1}\"\r\n", entity.Module.Name, entity.Name)); + list.Add(" }"); + return list.ExpandAndToString(""); + } +} diff --git a/src/OSharp.CodeGeneration/Templates/ng_AlainRouting.cshtml b/src/OSharp.CodeGeneration/Templates/ng_AlainRouting.cshtml new file mode 100644 index 0000000000000000000000000000000000000000..37a4c9177a5986d97991bbf2c943f4ba73779b2d --- /dev/null +++ b/src/OSharp.CodeGeneration/Templates/ng_AlainRouting.cshtml @@ -0,0 +1,47 @@ +@inherits MiniRazor.TemplateBase +@namespace OSharp.CodeGeneration.Templates +@using System; +@using System.Linq; +@using OSharp.CodeGeneration.Services.Entities +@using OSharp.CodeGeneration.Utils +@using OSharp.Collections; +@using OSharp.Exceptions; +@using OSharp.Extensions; +@{ + CodeModule module = Model; +}// ----------------------------------------------------------------------- +// +// 这个文件只生成一次,再次生成不会被覆盖。 +// +// +// +// @module.Project.Copyright +// +// @module.Project.SiteUrl +// @module.Project.Creator +// ----------------------------------------------------------------------- + +import { NgModule } from '@@angular/core'; +import { Routes, RouterModule } from '@@angular/router'; +import { ACLGuard } from '@@delon/acl'; +@foreach (CodeEntity entity in module.Entities.Where(m => m.Listable)) +{ + var lowerName = entity.Name.UpperToLowerAndSplit(); + import { @(entity.Name)Component } from './@(lowerName)/@(lowerName).component'; + +} + +const routes: Routes = [ +@foreach (CodeEntity entity in module.Entities.Where(m => m.Listable)) +{ + var lowerName = entity.Name.UpperToLowerAndSplit(); + { path: '@(lowerName)', component: @(entity.Name)Component, canActivate: [ACLGuard], data: { title: '@(entity.Display)管理', reuse: true, guard: 'Root.Admin.@(module.Name).@(entity.Name).Read' } }, + +} +]; + +@@NgModule({ + imports: [RouterModule.forChild(routes)], + exports: [RouterModule] +}) +export class @(module.Name)RoutingModule { } diff --git a/src/OSharp.CodeGenerator/Data/AutoMapperConfiguration.cs b/src/OSharp.CodeGenerator/Data/AutoMapperConfiguration.cs index 42f80840e7348d95ef1f9b17bc50d2f54ffb297a..bd9d7bba229111273f1c83a397a9efa3470492be 100644 --- a/src/OSharp.CodeGenerator/Data/AutoMapperConfiguration.cs +++ b/src/OSharp.CodeGenerator/Data/AutoMapperConfiguration.cs @@ -7,14 +7,8 @@ // 2021-04-06 13:13 // ----------------------------------------------------------------------- -using System; -using System.Runtime.Serialization; - -using AutoMapper.Configuration; - using OSharp.AutoMapper; using OSharp.CodeGeneration.Services.Entities; -using OSharp.CodeGenerator.Views; using OSharp.CodeGenerator.Views.Entities; using OSharp.CodeGenerator.Views.Modules; using OSharp.CodeGenerator.Views.Properties; @@ -27,22 +21,30 @@ namespace OSharp.CodeGenerator.Data /// 创建对象映射 public override void CreateMap() { + CreateMap().ForMember(e => e.Modules, opt => opt.Ignore()) + .ForMember(e => e.ProjectTemplates, opt => opt.Ignore()); + CreateMap().ForMember(e => e.ProjectId, opt => opt.MapFrom(vm => vm.Project.Id)) .ForMember(e => e.Project, opt => opt.Ignore()); CreateMap().ForMember(vm => vm.Namespace, opt => opt.Ignore()) .ForMember(vm => vm.Project, opt => opt.Ignore()); - CreateMap().ForMember(vm => vm.Namespace, opt => opt.Ignore()) - .ForMember(vm => vm.Project, opt => opt.Ignore()); + CreateMap().ForMember(e => e.Namespace, opt => opt.Ignore()) + .ForMember(e => e.Project, opt => opt.Ignore()) + .ForMember(e => e.Entities, opt => opt.Ignore()); CreateMap().ForMember(e => e.ModuleId, opt => opt.MapFrom(vm => vm.Module.Id)) .ForMember(e => e.Module, opt => opt.Ignore()); CreateMap().ForMember(vm => vm.Module, opt => opt.Ignore()); - CreateMap().ForMember(vm => vm.Module, opt => opt.Ignore()); + CreateMap().ForMember(e => e.Module, opt => opt.Ignore()) + .ForMember(e => e.Properties, opt => opt.Ignore()) + .ForMember(e => e.Foreigns, opt => opt.Ignore()); CreateMap().ForMember(e => e.EntityId, opt => opt.MapFrom(vm => vm.Entity.Id)) - .ForMember(e=>e.Entity, opt=>opt.Ignore()); + .ForMember(e => e.Entity, opt => opt.Ignore()); CreateMap().ForMember(vm => vm.Entity, opt => opt.Ignore()); - CreateMap().ForMember(vm => vm.Entity, opt => opt.Ignore()); + CreateMap().ForMember(e => e.Entity, opt => opt.Ignore()); + + CreateMap().ForMember(e => e.Entity, opt => opt.Ignore()); } } } diff --git a/src/OSharp.CodeGenerator/Data/Extensions.cs b/src/OSharp.CodeGenerator/Data/Extensions.cs new file mode 100644 index 0000000000000000000000000000000000000000..3d22162861390bc4ee6eb202c2c32ba4b0587467 --- /dev/null +++ b/src/OSharp.CodeGenerator/Data/Extensions.cs @@ -0,0 +1,51 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +using OSharp.CodeGeneration.Services.Entities; +using OSharp.CodeGenerator.Views.Entities; +using OSharp.CodeGenerator.Views.Modules; +using OSharp.CodeGenerator.Views.Projects; +using OSharp.CodeGenerator.Views.Properties; +using OSharp.Mapping; +using OSharp.Wpf.Stylet; + + +namespace OSharp.CodeGenerator.Data +{ + public static class Extensions + { + public static ProjectViewModel ToViewModel(this CodeProject project) + { + ProjectViewModel model = IoC.Get(); + model = project.MapTo(model); + return model; + } + + public static ModuleViewModel ToViewModel(this CodeModule module, ProjectViewModel projectModel = null) + { + ModuleViewModel model = IoC.Get(); + model = module.MapTo(model); + model.Project = projectModel; + return model; + } + + public static EntityViewModel ToViewModel(this CodeEntity entity, ModuleViewModel moduleModel = null) + { + EntityViewModel model = IoC.Get(); + model = entity.MapTo(model); + model.Module = moduleModel; + return model; + } + + public static PropertyViewModel ToViewModel(this CodeProperty property, EntityViewModel entityModel = null) + { + PropertyViewModel model = IoC.Get(); + model = property.MapTo(model); + model.Entity = entityModel; + return model; + } + } +} diff --git a/src/OSharp.CodeGenerator/Migrations/20210403122046_Init.Designer.cs b/src/OSharp.CodeGenerator/Migrations/20210403122046_Init.Designer.cs deleted file mode 100644 index 42b02ce9fa47629b97542941d3de6a360d97f5bd..0000000000000000000000000000000000000000 --- a/src/OSharp.CodeGenerator/Migrations/20210403122046_Init.Designer.cs +++ /dev/null @@ -1,338 +0,0 @@ -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using OSharp.Entity; - -namespace OSharp.CodeGenerator.Migrations -{ - [DbContext(typeof(DefaultDbContext))] - [Migration("20210403122046_Init")] - partial class Init - { - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "5.0.4"); - - modelBuilder.Entity("OSharp.Authorization.EntityInfos.EntityInfo", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("AuditEnabled") - .HasColumnType("INTEGER"); - - b.Property("Name") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("PropertyJson") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("TypeName") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("TypeName") - .IsUnique() - .HasDatabaseName("ClassFullNameIndex"); - - b.ToTable("Auth_EntityInfo"); - }); - - modelBuilder.Entity("OSharp.Authorization.Functions.Function", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("AccessType") - .HasColumnType("INTEGER"); - - b.Property("Action") - .HasColumnType("TEXT"); - - b.Property("Area") - .HasColumnType("TEXT"); - - b.Property("AuditEntityEnabled") - .HasColumnType("INTEGER"); - - b.Property("AuditOperationEnabled") - .HasColumnType("INTEGER"); - - b.Property("CacheExpirationSeconds") - .HasColumnType("INTEGER"); - - b.Property("Controller") - .HasColumnType("TEXT"); - - b.Property("IsAccessTypeChanged") - .HasColumnType("INTEGER"); - - b.Property("IsAjax") - .HasColumnType("INTEGER"); - - b.Property("IsCacheSliding") - .HasColumnType("INTEGER"); - - b.Property("IsController") - .HasColumnType("INTEGER"); - - b.Property("IsLocked") - .HasColumnType("INTEGER"); - - b.Property("IsSlaveDatabase") - .HasColumnType("INTEGER"); - - b.Property("Name") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("Area", "Controller", "Action") - .IsUnique() - .HasDatabaseName("AreaControllerActionIndex"); - - b.ToTable("Auth_Function"); - }); - - modelBuilder.Entity("OSharp.CodeGeneration.Entities.CodeEntity", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Display") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("IsDataAuth") - .HasColumnType("INTEGER"); - - b.Property("ModuleId") - .HasColumnType("TEXT"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("PrimaryKeyTypeFullName") - .IsRequired() - .HasMaxLength(500) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ModuleId"); - - b.ToTable("CodeGen_CodeEntity"); - }); - - modelBuilder.Entity("OSharp.CodeGeneration.Entities.CodeModule", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Display") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("ProjectId") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ProjectId"); - - b.ToTable("CodeGen_CodeModule"); - }); - - modelBuilder.Entity("OSharp.CodeGeneration.Entities.CodeProject", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Company") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("Copyright") - .HasMaxLength(500) - .HasColumnType("TEXT"); - - b.Property("Creator") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("NamespacePrefix") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("SiteUrl") - .HasMaxLength(500) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.ToTable("CodeGen_CodeProject"); - }); - - modelBuilder.Entity("OSharp.CodeGeneration.Entities.CodeProperty", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Display") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("EntityId") - .HasColumnType("TEXT"); - - b.Property("IsForeignKey") - .HasColumnType("INTEGER"); - - b.Property("IsInputDto") - .HasColumnType("INTEGER"); - - b.Property("IsNullable") - .HasColumnType("INTEGER"); - - b.Property("IsOutputDto") - .HasColumnType("INTEGER"); - - b.Property("IsRequired") - .HasColumnType("INTEGER"); - - b.Property("IsVirtual") - .HasColumnType("INTEGER"); - - b.Property("MaxLength") - .HasColumnType("INTEGER"); - - b.Property("MinLength") - .HasColumnType("INTEGER"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("TypeName") - .IsRequired() - .HasMaxLength(500) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("EntityId"); - - b.ToTable("CodeGen_CodeProperty"); - }); - - modelBuilder.Entity("OSharp.Core.Systems.KeyValue", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("IsLocked") - .HasColumnType("INTEGER"); - - b.Property("Key") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("ValueJson") - .HasColumnType("TEXT"); - - b.Property("ValueType") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("Key") - .IsUnique() - .HasDatabaseName("KeyIndex"); - - b.ToTable("Systems_KeyValue"); - }); - - modelBuilder.Entity("OSharp.CodeGeneration.Entities.CodeEntity", b => - { - b.HasOne("OSharp.CodeGeneration.Entities.CodeModule", "Module") - .WithMany("Entities") - .HasForeignKey("ModuleId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Module"); - }); - - modelBuilder.Entity("OSharp.CodeGeneration.Entities.CodeModule", b => - { - b.HasOne("OSharp.CodeGeneration.Entities.CodeProject", "Project") - .WithMany("Modules") - .HasForeignKey("ProjectId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Project"); - }); - - modelBuilder.Entity("OSharp.CodeGeneration.Entities.CodeProperty", b => - { - b.HasOne("OSharp.CodeGeneration.Entities.CodeEntity", "Entity") - .WithMany("Properties") - .HasForeignKey("EntityId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired(); - - b.Navigation("Entity"); - }); - - modelBuilder.Entity("OSharp.CodeGeneration.Entities.CodeEntity", b => - { - b.Navigation("Properties"); - }); - - modelBuilder.Entity("OSharp.CodeGeneration.Entities.CodeModule", b => - { - b.Navigation("Entities"); - }); - - modelBuilder.Entity("OSharp.CodeGeneration.Entities.CodeProject", b => - { - b.Navigation("Modules"); - }); -#pragma warning restore 612, 618 - } - } -} diff --git a/src/OSharp.CodeGenerator/Migrations/20210404022217_entity.Designer.cs b/src/OSharp.CodeGenerator/Migrations/20210404022217_entity.Designer.cs deleted file mode 100644 index 57d1de5d5fe5c8bcbfaf86b46c4a69b5be0428d4..0000000000000000000000000000000000000000 --- a/src/OSharp.CodeGenerator/Migrations/20210404022217_entity.Designer.cs +++ /dev/null @@ -1,359 +0,0 @@ -// -using System; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Infrastructure; -using Microsoft.EntityFrameworkCore.Migrations; -using Microsoft.EntityFrameworkCore.Storage.ValueConversion; -using OSharp.Entity; - -namespace OSharp.CodeGenerator.Migrations -{ - [DbContext(typeof(DefaultDbContext))] - [Migration("20210404022217_entity")] - partial class entity - { - protected override void BuildTargetModel(ModelBuilder modelBuilder) - { -#pragma warning disable 612, 618 - modelBuilder - .HasAnnotation("ProductVersion", "5.0.4"); - - modelBuilder.Entity("OSharp.Authorization.EntityInfos.EntityInfo", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("AuditEnabled") - .HasColumnType("INTEGER"); - - b.Property("Name") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("PropertyJson") - .IsRequired() - .HasColumnType("TEXT"); - - b.Property("TypeName") - .IsRequired() - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("TypeName") - .IsUnique() - .HasDatabaseName("ClassFullNameIndex"); - - b.ToTable("Auth_EntityInfo"); - }); - - modelBuilder.Entity("OSharp.Authorization.Functions.Function", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("AccessType") - .HasColumnType("INTEGER"); - - b.Property("Action") - .HasColumnType("TEXT"); - - b.Property("Area") - .HasColumnType("TEXT"); - - b.Property("AuditEntityEnabled") - .HasColumnType("INTEGER"); - - b.Property("AuditOperationEnabled") - .HasColumnType("INTEGER"); - - b.Property("CacheExpirationSeconds") - .HasColumnType("INTEGER"); - - b.Property("Controller") - .HasColumnType("TEXT"); - - b.Property("IsAccessTypeChanged") - .HasColumnType("INTEGER"); - - b.Property("IsAjax") - .HasColumnType("INTEGER"); - - b.Property("IsCacheSliding") - .HasColumnType("INTEGER"); - - b.Property("IsController") - .HasColumnType("INTEGER"); - - b.Property("IsLocked") - .HasColumnType("INTEGER"); - - b.Property("IsSlaveDatabase") - .HasColumnType("INTEGER"); - - b.Property("Name") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("Area", "Controller", "Action") - .IsUnique() - .HasDatabaseName("AreaControllerActionIndex"); - - b.ToTable("Auth_Function"); - }); - - modelBuilder.Entity("OSharp.CodeGeneration.Entities.CodeEntity", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedTime") - .HasColumnType("TEXT"); - - b.Property("Display") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("IsDataAuth") - .HasColumnType("INTEGER"); - - b.Property("IsLocked") - .HasColumnType("INTEGER"); - - b.Property("ModuleId") - .HasColumnType("TEXT"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("PrimaryKeyTypeFullName") - .IsRequired() - .HasMaxLength(500) - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ModuleId"); - - b.ToTable("CodeGen_CodeEntity"); - }); - - modelBuilder.Entity("OSharp.CodeGeneration.Entities.CodeModule", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("CreatedTime") - .HasColumnType("TEXT"); - - b.Property("Display") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("IsLocked") - .HasColumnType("INTEGER"); - - b.Property("Name") - .IsRequired() - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property("ProjectId") - .HasColumnType("TEXT"); - - b.HasKey("Id"); - - b.HasIndex("ProjectId"); - - b.ToTable("CodeGen_CodeModule"); - }); - - modelBuilder.Entity("OSharp.CodeGeneration.Entities.CodeProject", b => - { - b.Property("Id") - .ValueGeneratedOnAdd() - .HasColumnType("TEXT"); - - b.Property("Company") - .HasMaxLength(200) - .HasColumnType("TEXT"); - - b.Property