Net6。0中实现自动生成代码
1、前言
生成代码NuGet包:XmSoft.CodeGenerator
该包将会自动生成代码,如:实体,仓储,服务,控制器及校验等文件。
控制器包含CRUD接口:创建,修改,删除,详情,列表。
参考:ORM框架采用SqlSugar框架生成
2、示例//创建控制台应用 输出项目名称自定义 dotnet new console -o XmSoft.AutoCode //引入NuGet dotnet add package XmSoft.CodeGenerator//appsettings.json 配置代码命名空间及输出位置 //比如: { "CodeHelperOptions": { "ConnectConnectionString": "Server=127.0.0.1;Uid=sa;Pwd=xxxxxxx;Database=test;Port=3306;Charset=utf8;", "ProviderName": "MySql.Data.MySqlClient", "NameSpace": { "ModelsNamespace": "XmSoft.Domain.Models", "DomainName": "XmSoft.Domain", "DtoNamespace":"XmSoft.ViewModels.Dto", "ApiControllerNamespace": "XmSoft.Api.Application", "InterfaceName": "XmSoft", "ServicesNamespace": "XmSoft.Service", "RepositoriesNamespace": "XmSoft.Repository", "ValidatorNamespace": "XmSoft.Validation" }, "CodePath": { "ModelsPath": "XmSoft.Domain/Models/", "DtoPath": "XmSoft.ViewModels/Dto/", "IRepositoriesPath": "XmSoft.IRepository/", "IServicesPath": "XmSoft.IService/", "RepositoriesPath": "XmSoft.Repository/", "ServicesPath": "XmSoft.Service/", "ControllerPath": "XmSoft.Api/Application/", "ValidatorPath": "XmSoft.Validation/" } } } //Utility.cs 输入表名,多个用逗号隔开 public static class Utility { public static string[] WriteTables() { Console.WriteLine("------------请输入数据表名称,多个用逗号隔开------------"); var strRead = Console.ReadLine(); var tables = strRead?.Split(","); if (string.IsNullOrEmpty(strRead) || tables == null || tables.Length == 0) { WriteTables(); } return tables ?? Array.Empty(); } } //Program.cs Console.WriteLine("自动生成代码"); var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build(); var options = configuration.GetSection(nameof(CodeHelperOptions)).Get(); var path = Directory.GetCurrentDirectory(); var filterA= @"XmSoft.AutoCodebinDebug et6.0"; //XmSoft.AutoCode 修改创建的项目名 var filterB = @"XmSoft.AutoCodebinRelease et6.0"; path = path.Replace(filterA, ""); path = path.Replace(filterB, ""); Console.WriteLine(#34;{path}"); options.CodePath.ValidatorPath = Path.Combine(path, @options.CodePath.ValidatorPath); options.CodePath.ControllerPath = Path.Combine(path, @options.CodePath.ControllerPath); options.CodePath.ModelsPath = Path.Combine(path, @options.CodePath.ModelsPath); options.CodePath.IRepositoriesPath = Path.Combine(path, @options.CodePath.IRepositoriesPath); options.CodePath.IServicesPath = Path.Combine(path, @options.CodePath.IServicesPath); options.CodePath.RepositoriesPath = Path.Combine(path, @options.CodePath.RepositoriesPath); options.CodePath.ServicesPath = Path.Combine(path, @options.CodePath.ServicesPath); options.CodePath.DtoPath = Path.Combine(path, @options.CodePath.DtoPath); var tables = Utility.WriteTables(); options.Tables = tables; Console.WriteLine("------------是否确定执行(Y/N)------------"); var command = Console.ReadLine(); if (!string.IsNullOrEmpty(command) && command.ToLower() == "y") { var helper = new CodeGeneratorHelper(options); helper.Run(); Console.WriteLine("------------完成------------"); } Console.ReadKey();
3、执行z_test表sql语句 DROP TABLE IF EXISTS `z_test`; CREATE TABLE `z_test` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT "id", `business_id` bigint(20) NULL DEFAULT NULL COMMENT "业务id", `title` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT "标题", `content` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT "内容", `picture` text CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL COMMENT "图片", `status` int(11) NULL DEFAULT NULL COMMENT "状态 0 正常 1 关闭", `remark` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT "备注说明", `sort` int(11) NULL DEFAULT NULL COMMENT "排序", `create_time` datetime(0) NULL DEFAULT NULL COMMENT "创建时间", `create_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT "创建Id", `update_time` datetime(0) NULL DEFAULT NULL COMMENT "更新时间", `update_by` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT "更新Id", `delFlag` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL COMMENT "是否删除 1 是,0 否", PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci COMMENT = "测试表" ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1; 补充说明:表必须有个主键key
执行//生成实体 /// /// 测试表 /// [SugarTable("z_test")] public partial class Test : BaseBusinessEntity { /// /// 标题 /// [SugarColumn(ColumnName = "title")] public string Title { get; set; } /// /// 内容 /// [SugarColumn(ColumnName = "content")] public string Content { get; set; } /// /// 图片 /// [SugarColumn(ColumnName = "picture")] public string Picture { get; set; } /// /// 状态 0 正常 1 关闭 /// [SugarColumn(ColumnName = "status")] public int? Status { get; set; } /// /// 备注说明 /// [SugarColumn(ColumnName = "remark")] public string Remark { get; set; } /// /// 排序 /// [SugarColumn(ColumnName = "sort")] public int? Sort { get; set; } } 说明:自定义 BaseBusinessEntity或BaseEntity 自定义,这里的主键名id ,业务id /// /// /// /// public abstract class BaseBusinessEntity : BaseEntity { /// /// 业务Id /// [SugarColumn(ColumnName = "business_id")] public long? BusinessId { get; set; } } public abstract class BaseEntity { [SugarColumn(IsPrimaryKey = true, IsIdentity = true, ColumnName = "id")] public T Id { get; set; } /// /// 0未删除 1回收站 2已删除 /// [SugarColumn(ColumnName = "delFlag")] [JsonIgnore] public string DelFlag { get; set; } /// /// 创建时间 /// [SugarColumn(ColumnName = "create_time")] // [Column("create_time")] //[JsonIgnore] public DateTime? CreateTime { get; set; } /// /// 创建Id /// [SugarColumn(ColumnName = "create_by")] //[Column("create_id")] [JsonIgnore] public string Create_By { get; set; } /// /// 修改时间 /// [SugarColumn(ColumnName = "update_time")] //[Column("update_time")] [JsonIgnore] public DateTime? UpdateTime { get; set; } /// /// 修改者ID /// [SugarColumn(ColumnName = "update_by")] //[Column("update_id")] [JsonIgnore] public string Update_By { get; set; } public void Create() { //Create_By = (userId?.ToString()) ?? Create_By; //BusinessId = businessId ?? BusinessId; CreateTime = DateTime.Now; DelFlag = "0"; } public void Update() { UpdateTime = DateTime.Now; } } //生成仓储 EFRepository 引用XmSoft.Core.SqlSugar.Repository public sealed class TestRepository :EFRepository,ITestRepository { public readonly ISqlSugarClient Context; public TestRepository(ISqlSugarClient context) : base(context) { Context = context; } public ISugarQueryable SugarQueryable() { return Context.Queryable(); } }//生成服务 引用XmSoft.Core.SqlSugar.Service public class TestService : BaseService,ITestService { public TestService(ITestRepository _repository):base(_repository) { } public async override Task> Create(Test entity, dynamic user) { var validation = new AddTestValidator().Validation(entity); if (!validation.Succeeded) return validation.Fail(); entity.Create(); entity.Create_By = user?.UserName; entity.BusinessId = user?.BusinessId; return await base.Create(entity); } public async override Task> Update(Test entity, dynamic user) { var validation = new UpdateTestValidator().Validation(entity); if (!validation.Succeeded) return validation.Fail(); entity.Update(); entity.Update_By = user?.UserName; return await base.Update(entity); } public async Task>> List(Test model,PageInfo pager,dynamic user) { long? businessId = user?.BusinessId; var predicate = Expressionable.Create(); predicate.And(q => q.BusinessId == businessId); var result = await Page(pager.PageIndex, pager.PageSize, predicate.ToExpression(), q => q.CreateTime, false); return result; } }//生成Dto /// /// 测试表 /// public partial class TestDto { /// /// id /// public long Id { get; set; } /// /// 业务id /// public long? BusinessId { get; set; } /// /// 标题 /// public string Title { get; set; } /// /// 内容 /// public string Content { get; set; } /// /// 图片 /// public string Picture { get; set; } /// /// 状态 0 正常 1 关闭 /// public int? Status { get; set; } /// /// 备注说明 /// public string Remark { get; set; } /// /// 排序 /// public int? Sort { get; set; } }//生成控制器 BaseAppService 可自定义可继承 ControllerBase等 /// /// 测试表 /// [Route("test")] [Tags("测试表")] public class TestAppService :BaseAppService { private readonly ITestService service; public TestAppService(ITestService _service) { service = _service; } /// /// 创建测试表 /// /// /// [HttpPost] [SwaggerResponse(200, Type = typeof(IResult))] [Log(Title = "测试表", BusinessType = BusinessType.INSERT)] public IActionResult Create(TestDto model) => service.Create(model.Adapt(),User).ApiResult(); /// /// 修改测试表 /// /// /// [HttpPut] [SwaggerResponse(200, Type = typeof(IResult))] [Log(Title = "测试表", BusinessType = BusinessType.UPDATE)] public IActionResult Update(TestDto model) => service.Update(model.Adapt(),User).ApiResult(); /// /// 删除测试表 /// /// /// [HttpDelete("{id}")] [SwaggerResponse(200, Type = typeof(IResult))] [Log(Title = "测试表", BusinessType = BusinessType.DELETE)] public IActionResult Delete(int id) => service.Delete(q=>q.Id == id).ApiResult(); /// /// 获取测试表数据 /// /// /// [HttpGet("{id}")] [SwaggerResponse(200, Type = typeof(IResult))] public IActionResult Info(int id) => service.Info(q => q.Id == id).ApiResult(); /// /// 测试表列表 /// /// /// /// [HttpGet("list")] [SwaggerResponse(200, Type = typeof(IResult>))] public IActionResult List(TestDto model,PageInfo pager) => service.List(model.Adapt(), pager, User).ApiResult(); }
Swagger显示效果注:需要Demo请私信发邮箱
不止包机参展!广东企业正在全球抢订单就在不久前,广州白云国际机场迎来一批步履匆匆的旅客,伴随着飞机轰鸣声,一场跨越中国与新加坡的商机之旅正式开启。这是新加坡暂停两年之久的亚太区美容展再次迎来久违的中国客人。今年11月
创投周报国氢科技融资45亿,黑石CEO回应9000亿基金限制赎回中新经纬12月10日电(邓芷若)本周(12月3日12月9日),国内创投圈共发生150起投融资事件,已披露的投融资总金额约177亿元。氢能科技企业国氢科技完成45亿元的B轮融资,为本
国产8K全画幅B1斩获BIRTV2022推荐项目12月8日,BIRTV2022展览会产品技术与应用项目推荐(展示)活动在线上召开,BOSMA博冠8K全画幅摄像机B1成功入选BIRTV2022展览会推荐项目产品类。国产8K全画幅B
现金流是投资者的底气昨日与几个朋友在一起饮茶,大家一致认为现金流既是投资者的底气,也是投资者的武器。那么,今日就再谈谈现金流吧。我妻子是医生,在湖南省的中等规模的城市里,她的收入是比较丰厚的。所以16
700万本金半年亏逾一成,投资者状告长江资管,最新判决来了因购买的资管产品踩雷,投资者将资管公司告上法庭,判决来了。中国裁判文书网近日披露了长江证券(上海)资产管理有限公司(简称长江资管)与魏某国其他合同纠纷二审民事判决书。依据判决书,魏
实现人生理想勇做新时代奋斗者青春不待,时光难再续,最美的年华里圆最美的梦,如果你在追寻梦想,就请奋斗吧,趁我们还年轻,趁我们还有力气奔跑,趁我们还有勇气去争取,努力去实现自已的人生价值。实现人生理想,需要我们
探讨人类命运的走向我们这些人,我们这一代人。人不读书,精神世界就会匮乏。可是我们这一代人,读书读得多了,反而不快乐了。看得太多,懂得太多,不能糊糊涂涂过了。但值得开心的,却也是我们读了很多书。说起来
会议室装了高档音箱,但效果还是不好,该怎么办?扩声系统在沟通过程中扮演讯息传递的关键角色,足以影响一场会议的成败。在一间会议室中,扩声系统的安装,是视听工程规划中最重要的一环。在很多案例里,有些会议室明明安装了高级且昂贵的喇叭
陶罐之悟以被动之力翻转命运文易白生命有时候就像一个陶罐,一摔就破碎。当我们以破罐破摔的心态,用执念或怨念消极对待本就脆弱的自己时,生命将变得不堪一击。陶罐是用泥土捏造的,而生活中的我们,又何尝不像一尊陶罐?
不好好学地理,可能连世界杯都看不懂了小时候为了看懂古装电视剧,我们需要刻苦学习历史,才能厘清朝代更迭和各政权战争史。长大后看足球发现,如果不学好地理,都不知何为伊比利亚半岛德比,特立尼达和多巴哥在何处,更不知为何19
Intel承诺未来两代独立显卡绝对不放弃IntelArcA系列独立显卡(代号Alchmeist)发布之后,因为性能平平驱动不成熟,反响很一般,而研发是需要巨额投入的,对于财务吃紧的Intel来说压力可想而知。一度有传闻称