如何使用ASP.NET核心中的C#生成自定义密钥号 [英] How to Generate Custom Key Number Using C# in ASP.NET Core

查看:141
本文介绍了如何使用ASP.NET核心中的C#生成自定义密钥号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的课程,

  public class PatReg 
{
[DatabaseGenerated(DatabaseGeneratedOption.Computed) ,ScaffoldColumn(false)]
public Int64 RecId {get;组; }
[Key,Display(Name =File Id),ScaffoldColumn(true),DatabaseGenerated(DatabaseGeneratedOption.None)]
public Int64 FileId {get;组; }
[必需,显示(名称=名字)]
public string FName {get;组; }
[必需,显示(名称=中间名)]
public string MName {get;组; }
[必需,显示(名称=姓氏)]
public string LName {get;组; }
[必需,显示(名称=出生日期),DisplayFormat(DataFormatString ={0:yyyy-MM-dd},ApplyFormatInEditMode = true)]
public DateTime Dob {组;
}

FileId是我的主键,我想在保存时生成它记录与记录一起保存,



自定义号码将具有以下规格,YYMMDD0001其中YY是年份的两位数,MM是该月份的两位数字。 DD是一天的两位数,001是每天的串行启动和重置。



这是我的控制器

  // POST:PatReg / Create 
//为了防止过多的攻击,请启用要绑定的特定属性,
//更多详细信息http://go.microsoft.com/fwlink/?LinkId=317598。
[HttpPost]
[ValidateAntiForgeryToken]
public async任务< IActionResult>创建([Bind(FileId,FName,MName,LName,Dob)] PatReg patReg)
{

if(ModelState.IsValid)
{
_context 。新增(patReg);
await _context.SaveChangesAsync();
return RedirectToAction(Index);
}
return View(patReg);
}

背景



我以前使用SQL存储过程生成这个数字,如下所示,

  Set @YY =(RIGHT(CONVERT(VARCHAR(8) ,GETDATE(),1),2))
设置@MM = SUBSTRING(CONVERT(nvarchar(6),getdate(),112),5,2)
Set @DD = RIGHT 00'+ CONVERT(NVARCHAR(2),DATEPART(DAY,GETDATE())),2)
设置@SRL =(SELECT FileNumSrl FROM SetTblSrls WHERE RECID = 1)
SET @FileId = CAST(CONCAT(@YY,@MM,@ DD,00,@ SRL)AS int))

@ SRL表示从SetTblSrls查找的串行序列,我曾经在目标表上有一个触发器来更新每个插入上的这个数字,每当我生成FileId时,我得到一个新的数字>

如何使用EF和C#,

解决方案

需要在某个地方持续一个序列号,以便每次都可以安全地增加它你有一个新的文件。内存不是真正的选择,因为IIS默认情况下每隔29小时重置其应用程序池,从而丢失可能已经缓存的任何内容。因此,您将留下数据库或文件系统。



以下SQL为您提供了一种安全且有效的方式,通过简单执行获取下一个可用的序列号存储过程从服务器端的C#代码读取返回的值:

 创建表DailySequence 

SequenceDate date not null主键,
LastSequence int not null默认(0) - 如果您希望第一个序列为1
,则更改默认值
go

创建过程dbo.GetNextSequence as
begin
Declare @today date = getdate()
声明@table表(id int)

begin tran

更新DailySequence set LastSequence = LastSequence + 1输出inserted.LastSequence到@table其中SequenceDate = @ today

if(@@ ROWCOUNT = 0)
insert into DailySequence SequenceDate)
输出insert.LastSequence到@table
值(@today)

提交

声明@s varchar(20)
从@table

中选择@s = convert(varchar(20),id) if(Len(@s)< 4)
set @s = Right('000'+ @s,4)

选择CONVERT(VARCHAR(10),@today,12 )+ @s [Sequence]
end
go


this my class,

public class PatReg
{
    [DatabaseGenerated(DatabaseGeneratedOption.Computed), ScaffoldColumn(false)]
    public Int64 RecId { get; set; }
    [Key,Display(Name = "File Id"), ScaffoldColumn(true), DatabaseGenerated(DatabaseGeneratedOption.None )]
    public Int64 FileId { get; set; }
    [Required, Display(Name = "First Name")]
    public string FName { get; set; }
    [Required, Display(Name = "Middle Name")]
    public string MName { get; set; }
    [Required, Display(Name = "Last Name")]
    public string LName { get; set; }
    [Required, Display(Name = "Date of Birth"), DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
    public DateTime Dob { get; set; }
  }

"FileId" is my primary key and I want to generate it upon saving the record save it along with the record,

Custom number would have the following spec, YYMMDD0001 where YY is two digit of the year, MM Two digit of the month. DD is two digits of day, 001 is the serial start and reset every day.

This is my controller

// POST: PatReg/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<IActionResult> Create([Bind("FileId,FName,MName,LName,Dob")] PatReg patReg)
    {

        if (ModelState.IsValid)
        {
            _context.Add(patReg);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        return View(patReg);
    }

Background

I used to generate this number using SQL stored procedure like below,

 Set @YY = (RIGHT(CONVERT(VARCHAR(8), GETDATE(), 1),2))
    Set @MM =  SUBSTRING(CONVERT(nvarchar(6),getdate(), 112),5,2)
    Set @DD =  RIGHT('00' + CONVERT(NVARCHAR(2), DATEPART(DAY, GETDATE())), 2)
    Set @SRL = (SELECT FileNumSrl FROM SetTblSrls WHERE RecID = 1)
    SET @FileId =(select CAST(CONCAT ( @YY , @MM , @DD,00 ,@SRL) AS int))

"@SRL" represents the serial sequence that I lookup from "SetTblSrls" and I used to have a trigger on the target table to update this number on each insert by which i get a new number every time I generate the FileId

How can I do it using EF and C#,

解决方案

You're going to need to persist a sequence number somewhere so that you can safely increment it each time you've got a new file. In-memory isn't really an option since IIS resets its app pools every 29 hours by default, losing anything you may have cached. As such you're left with the database or the file system.

The following SQL provides you with a safe and performant means of getting the next available sequence number by simply executing the stored procedure from your server-side C# code and reading the value returned:

create table DailySequence
(
    SequenceDate date not null primary key,
    LastSequence int not null default(0) -- Change the default if you want your first sequence to be 1
)
go

create procedure dbo.GetNextSequence as
begin
    Declare @today date = getdate()
    Declare @table table (id int)

    begin tran

    update DailySequence set LastSequence=LastSequence+1 output inserted.LastSequence into @table where SequenceDate=@today

    if (@@ROWCOUNT=0)
        insert into DailySequence(SequenceDate) 
        output inserted.LastSequence into @table 
        values (@today)

    commit

    declare @s varchar(20) 
    select @s = convert(varchar(20), id) from @table

    if (Len(@s)<4)
        set @s = Right('000' + @s, 4)

    select CONVERT(VARCHAR(10), @today, 12) + @s [Sequence]
end
go

这篇关于如何使用ASP.NET核心中的C#生成自定义密钥号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆