当前位置:科学 > 正文
Net 6.0中实现自动生成代码
2023-03-20 22:46:38 来源:简单d猫
(资料图)
1、前言
生成代码NuGet包:XmSoft.CodeGenerator
该包将会自动生成代码,如:实体,仓储,服务,控制器及校验等文件。
控制器包含CRUD接口:创建,修改,删除,详情,列表。
参考:ORM框架采用SqlSugar框架生成
2、示例
//创建控制台应用 输出项目名称自定义dotnet new console -o XmSoft.AutoCode //引入NuGetdotnet 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<string>(); }}
//Program.cs Console.WriteLine("自动生成代码");var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build();var options = configuration.GetSection(nameof(CodeHelperOptions)).Get<CodeHelperOptions>();var path = Directory.GetCurrentDirectory();var filterA= @"\XmSoft.AutoCode\bin\Debug\net6.0"; //XmSoft.AutoCode 修改创建的项目名var filterB = @"\XmSoft.AutoCode\bin\Release\net6.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
执行
//生成实体/// <summary>/// 测试表/// </summary>[SugarTable("z_test")]public partial class Test : BaseBusinessEntity<int?>{ /// <summary> /// 标题 /// </summary> [SugarColumn(ColumnName = "title")] public string Title { get; set; } /// <summary> /// 内容 /// </summary> [SugarColumn(ColumnName = "content")] public string Content { get; set; } /// <summary> /// 图片 /// </summary> [SugarColumn(ColumnName = "picture")] public string Picture { get; set; } /// <summary> /// 状态 0 正常 1 关闭 /// </summary> [SugarColumn(ColumnName = "status")] public int? Status { get; set; } /// <summary> /// 备注说明 /// </summary> [SugarColumn(ColumnName = "remark")] public string Remark { get; set; } /// <summary> /// 排序 /// </summary> [SugarColumn(ColumnName = "sort")] public int? Sort { get; set; } } 说明:自定义 BaseBusinessEntity或BaseEntity 自定义,这里的主键名id ,业务id /// <summary>/// /// </summary>/// <typeparam name="T"></typeparam>public abstract class BaseBusinessEntity<T> : BaseEntity<T>{ /// <summary> /// 业务Id /// </summary> [SugarColumn(ColumnName = "business_id")] public long? BusinessId { get; set; }}public abstract class BaseEntity<T> { [SugarColumn(IsPrimaryKey = true, IsIdentity = true, ColumnName = "id")] public T Id { get; set; } /// <summary> /// 0未删除 1回收站 2已删除 /// </summary> [SugarColumn(ColumnName = "delFlag")] [JsonIgnore] public string DelFlag { get; set; } /// <summary> /// 创建时间 /// </summary> [SugarColumn(ColumnName = "create_time")] // [Column("create_time")] //[JsonIgnore] public DateTime? CreateTime { get; set; } /// <summary> /// 创建Id /// </summary> [SugarColumn(ColumnName = "create_by")] //[Column("create_id")] [JsonIgnore] public string Create_By { get; set; } /// <summary> /// 修改时间 /// </summary> [SugarColumn(ColumnName = "update_time")] //[Column("update_time")] [JsonIgnore] public DateTime? UpdateTime { get; set; } /// <summary> /// 修改者ID /// </summary> [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<Test> 引用XmSoft.Core.SqlSugar.Repositorypublic sealed class TestRepository :EFRepository<Test>,ITestRepository{ public readonly ISqlSugarClient Context; public TestRepository(ISqlSugarClient context) : base(context) { Context = context; } public ISugarQueryable<Test> SugarQueryable() { return Context.Queryable<Test>(); }}
//生成服务 引用XmSoft.Core.SqlSugar.Servicepublic class TestService : BaseService<Test>,ITestService{ public TestService(ITestRepository _repository):base(_repository) { } public async override Task<IResult<bool>> Create(Test entity, dynamic user) { var validation = new AddTestValidator().Validation(entity); if (!validation.Succeeded) return validation.Fail<bool>(); entity.Create(); entity.Create_By = user?.UserName; entity.BusinessId = user?.BusinessId; return await base.Create(entity); } public async override Task<IResult<int>> Update(Test entity, dynamic user) { var validation = new UpdateTestValidator().Validation(entity); if (!validation.Succeeded) return validation.Fail<int>(); entity.Update(); entity.Update_By = user?.UserName; return await base.Update(entity); } public async Task<IResult<Page<Test>>> List(Test model,PageInfo pager,dynamic user) { long? businessId = user?.BusinessId; var predicate = Expressionable.Create<Test>(); predicate.And(q => q.BusinessId == businessId); var result = await Page(pager.PageIndex, pager.PageSize, predicate.ToExpression(), q => q.CreateTime, false); return result; }}
//生成Dto/// <summary>/// 测试表/// </summary>public partial class TestDto{ /// <summary> /// id /// </summary> public long Id { get; set; } /// <summary> /// 业务id /// </summary> public long? BusinessId { get; set; } /// <summary> /// 标题 /// </summary> public string Title { get; set; } /// <summary> /// 内容 /// </summary> public string Content { get; set; } /// <summary> /// 图片 /// </summary> public string Picture { get; set; } /// <summary> /// 状态 0 正常 1 关闭 /// </summary> public int? Status { get; set; } /// <summary> /// 备注说明 /// </summary> public string Remark { get; set; } /// <summary> /// 排序 /// </summary> public int? Sort { get; set; } }
//生成控制器 BaseAppService 可自定义可继承 ControllerBase等/// <summary>/// 测试表/// </summary>[Route("test")][Tags("测试表")]public class TestAppService :BaseAppService{ private readonly ITestService service; public TestAppService(ITestService _service) { service = _service; } /// <summary> /// 创建测试表 /// </summary> /// <param name="model"></param> /// <returns></returns> [HttpPost] [SwaggerResponse(200, Type = typeof(IResult<bool>))] [Log(Title = "测试表", BusinessType = BusinessType.INSERT)] public IActionResult Create(TestDto model) => service.Create(model.Adapt<Test>(),User).ApiResult(); /// <summary> /// 修改测试表 /// </summary> /// <param name="model"></param> /// <returns></returns> [HttpPut] [SwaggerResponse(200, Type = typeof(IResult<int>))] [Log(Title = "测试表", BusinessType = BusinessType.UPDATE)] public IActionResult Update(TestDto model) => service.Update(model.Adapt<Test>(),User).ApiResult(); /// <summary> /// 删除测试表 /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpDelete("{id}")] [SwaggerResponse(200, Type = typeof(IResult<int>))] [Log(Title = "测试表", BusinessType = BusinessType.DELETE)] public IActionResult Delete(int id) => service.Delete(q=>q.Id == id).ApiResult(); /// <summary> /// 获取测试表数据 /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpGet("{id}")] [SwaggerResponse(200, Type = typeof(IResult<Test>))] public IActionResult Info(int id) => service.Info(q => q.Id == id).ApiResult(); /// <summary> /// 测试表列表 /// </summary> /// <param name="model"></param> /// <param name="pager"></param> /// <returns></returns> [HttpGet("list")] [SwaggerResponse(200, Type = typeof(IResult<Page<Test>>))] public IActionResult List(TestDto model,PageInfo pager) => service.List(model.Adapt<Test>(), pager, User).ApiResult(); }
Swagger显示效果
注:需要Demo请私信发邮箱
关键词:
推荐阅读
手机卡服务密码怎么查?短信的找回方式的步骤
手机卡服务密码怎么查?当我们在办理手机业务或者兑换礼品的时,都需要用到手机号码的服务密码。那怎查询呢,比如可以去营业厅办理密码重置 【详细】
女娲补天背后有秘密 女娲补天的恐怖真相介绍
女娲补天背后有秘密相信每个人都听过女娲补天的故事,故事很有趣,结局也很很好。女娲拯救了人类,但是最近有人发现女娲补天背后有秘密,似 【详细】
飞机发明者是谁?飞机有哪些类型?
飞机发明者是谁?飞机是由莱特兄弟发明的,莱特兄弟是美国著名的发明家,他们的哥哥是威尔伯菜特,他们的弟弟是奥维尔莱特。1903年12月17日 【详细】
Google I/O线上开发者大会发布 安卓12新特性支持什么功能?
现在大多数人用的手机还是安卓机,本次Android 12的发布自然也是引起了一大波的关注,国内不少厂商也参与了测试,我们来看看谷歌正式发布A 【详细】
航天员出舱七个小时怎么喝水?太空行走的危险和好处是什么?
航天员出舱七个小时怎么喝水?7月4日,中国宇航员刘伯明和汤洪波出航活动,整个进程持续了7个多小时。据报道,宇航员在舱外服里有饮水袋,在 【详细】
相关新闻
- 27款进口网游获批版号,腾讯、网易在列!背后释放重大信号
- Net 6.0中实现自动生成代码
- 全球今热点:轻运达动态-热烈欢迎江西吉利莅临轻运达审厂
- 三星Galaxy Flip5将拥有更大的外屏
- 直播间卖货已经走进了死胡同? 精选
- 德库拉的恶梦(德库拉的恶梦的主演介绍) 今日快讯
- 美专家:三大因素推动中国科技赶超美国
- 观点:谁在决定着SaaS行业的前途?
- 世界快消息!这些中国硬币可能在未来几周内爆炸
- 天天速看:某鱼APP再爆新料,颜色交易伪装进硬币收藏?令人大开眼界
- 今日热议:欧莱雅洗面奶怎么样(欧莱雅洗面奶怎么样_欧莱雅洗面奶好用吗)
- 焦点速读:萌学园第二部(萌学园共有几部?分别叫什么?歌曲都有那些?)
- 每日热门:广域铭岛入围2022年成渝地区工业互联网及智能制造资源池服务商
- 四川省绵阳市2023年省市重点项目名单(共404个)|头条焦点
- 申通快递增速领跑,两通一达胶着化,顺丰再加码这一市场?-当前最新
- 一篇文章说清楚头条“限流”那些事儿
- 环球热资讯!续航200公里,新日推出新款高颜值电动车,能跑长路无续航焦虑
- 焦点热门:超能使者25集全集(超能使者怎么成25集了)
- 【速看料】杨梅的味道课文?
- 全球关注:如何防止订单重复支付?