5

.NET ORM框架HiSql实战-第三章-使用自定义编号生成【申请编号】 - pengxianyuan

 2 years ago
source link: https://www.cnblogs.com/pengxianyuan/p/16458628.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

.NET ORM框架HiSql实战-第三章-使用自定义编号生成【申请编号】

一、引言

上一篇.NET ORM框架HiSql实战-第二章-使用Hisql实现菜单管理(增删改查) 中菜单编号采用的是雪花ID,生成的编号无法自定义。比如本系统的一个申请业务,需要按前缀+日期+流水号的规则生成【申请编号】,这样就可以用到hisql的自定义编号。

hisql自定义编号不但可以生成雪花ID,很重要的是支持类似以下规则的编号:
规则1:20220001、202200001....到202299999 或到 2022ZZZZZ。
规则2:BH20220708000001、BH20220708000001....到BH20220708999999 或到 BH20220708zZZZZZ。
规则...

您也可以通过查看 Hisql流水编号 的各个参数的说明,解锁更多的编号规则,实现您想要的编号。

先看结果图:

493017-20220708152343096-1085753620.png

二、使用步骤
1、 在文件第一章中的文件: HiSqlSetupExtension 加入编号对象的注入,这里必须是采用单例模式注入

493017-20220708152725625-107927106.png

HiSqlSetupExtension 完整代码

using HiSql;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;

namespace H.CRM.Action.API.Helper
{

    public static class HiSqlSetupExtension
    {
        public static IServiceCollection AddHiSqlSetup(this IServiceCollection services)
        {
            //注入HiSqlConfig
            services.AddTransient<HiSqlConfig>();
            //注入HiSqlClient
            services.AddTransient<HiSqlClient>((d) =>
            {
                var config = d.GetService<HiSqlConfig>();
                var hisql = new HiSqlClient(config);
                return hisql;
            });

            services.AddSingleton((d) =>
            {
                #region 集群模式部署需要开启Redis
                HiSql.Global.RedisOn = true;//开启redis缓存
                HiSql.Global.RedisOptions = new RedisOptions { Host = "127.0.0.1", PassWord = "", Port = 6379, CacheRegion = "HISQL" };
                HiSql.Global.NumberOptions.MultiMode = true;
                #endregion

                HiSql.Global.SnroOn = true;
                var config = d.GetService<HiSqlConfig>();
                HiSqlClient sqlClient = new HiSqlClient(config);
                sqlClient.CodeFirst.InstallHisql();
                var number = new SeriNumber(sqlClient);

                return number;
            });

            return services;
        }
    }

    class HiSqlConfig : ConnectionConfig
    {
        static readonly NLog.Logger logger = NLog.LogManager.GetLogger("HiSqlSetup");
        public HiSqlConfig(IConfiguration configuration)
        {
            DbType = DBType.SqlServer;
            DbServer = "HISQL";
            ConnectionString = configuration.GetSection("ConnectionStrings:Admin").Value;
            Schema = "dbo";
            SqlExecTimeOut = 1000 * 5;
            AppEvents = new AopEvent()
            {
                OnDbDecryptEvent = (connstr) =>
                {
                    //解密连接字段
                    return connstr;
                },
                OnLogSqlExecuting = (sql, param) =>
                {
                    //sql执行前 日志记录 (异步)
#if DEBUG
                    logger.Trace($"执行前sql:{sql} time:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")}");
#endif
                },
                OnLogSqlExecuted = (sql, param) =>
                {
#if DEBUG
                    //sql执行后 日志记录 (异步)
                    logger.Trace($"执行后sql:{sql} time:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")}");
#endif
                },
                OnSqlError = (sqlEx) =>
                {
                    //sql执行错误后 日志记录 (异步)
                    logger.Error($"执行错误:{sqlEx.Message} sql:{sqlEx.Sql} time:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")}");
                },
                OnTimeOut = (int timer) =>
                {
                    //logger.Trace($"执行超时:{timer} time:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ffff")}");
                }
            };
        }
    }
}

2、 配置编号服务。
在 HiSqlController 文件添加Action ConfigSNRO(), 然后在访问改地址,就完成编号的初始化。这个配置只有修改编号规则的时候初始化一次,也可以采用其他方式初始化。

493017-20220708153538266-1805939211.png

HiSqlController 完整代码

using Microsoft.AspNetCore.Mvc;
using HiSql;
using System.Linq;
using System.Collections.Generic;
using HSMB.Model.Dto;

namespace HSMB.Admin.WebApi.Controllers
{
    [Verify]
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class HiSqlController : ControllerBase
    {
        private readonly HiSqlClient sqlClient;
        private readonly SeriNumber seriNumber;

        
        public HiSqlController(
             HiSqlClient hiSqlClient
            , SeriNumber seriNumber
            )
        {
            this.sqlClient = hiSqlClient;
            this.seriNumber = seriNumber;
        }
        [HttpGet, HttpPost]
        public IActionResult Install()
        {
            HiSql.Global.SnroOn = true; //启用编号。
            sqlClient.CodeFirst.InstallHisql();
            var tables = sqlClient.DbFirst.GetTables().ToList().Where(t => t.TabName.StartsWith("H"));
            return new JsonResult(tables);
        }

        [HttpGet, HttpPost]
        public IActionResult ConfigSNRO()
        {
            //配置表   "bus_request_person"  字段 "reqID" 使用 自定义编号,名称:request_person:
            ConfigSnroInit(new Hi_Snro()
            {
                SNRO = BillNumberType.request_person, // public const string request_person = "request_person";
                SNUM = 1,
                IsSnow = false,
                SnowTick = 0,
                StartNum = "0000",
                EndNum = "9999",
                Length = 4,
                CurrNum = "0000",
                CurrAllNum = "",
                PreChar = "",
                IsNumber = true,
                PreType = PreType.YM,
                FixPreChar = "P",
                IsHasPre = true,
                CacheSpace = 10,
                Descript = "申请单号"
            }, "bus_request_person", "reqID");
            return new JsonResult(true);
        }

        private void ConfigSnroInit(Hi_Snro snro, string tableName, string fieldName)
        {
            ///配置加入到编号表
            var cnt = sqlClient.Modi("Hi_Snro", snro).ExecCommand();
            //
            var json = sqlClient.Context.DMInitalize.GetTabStruct(tableName); //获取一下表表机构,系统自动将表结构信息插入到  Hi_FieldModel 中
            // 修改  Hi_FieldModel 中配置,
            sqlClient.Update(typeof(Hi_FieldModel).Name, new { TabName = tableName, FieldName = fieldName, SNO = snro.SNRO, SNO_NUM = snro.SNUM }).Only("SNO", "SNO_NUM").ExecCommand();
        }
        [HttpGet, HttpPost]
        public IActionResult TestSNRO(string SNRO = BillNumberType.request_person, int SNO_NUM = 1)
        {
            var num = seriNumber.NewNumber(SNRO, SNO_NUM);           
            return new JsonResult(num);
        }
       

    }
}

启动项目通过测试代码可以看到编号没问题;

493017-20220708153919504-1509038169.png

3、修改 BusrequestpersonController 代码,将生成【申请编号】的地方采用 SeriNumber对象生成。
注入对象:

493017-20220708154448246-1298774764.png

采用 SeriNumber对象生成编号:

493017-20220708154524417-1651413437.png

完成后,启用项目填写业务申请,可以看到生成的编号如开头的截图一样,是按照我们想要的规则生成编号的。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK