Alternatives to using Max+1 to create a user friendly unique sequence numbers

后端 未结 2 1013
孤独总比滥情好
孤独总比滥情好 2020-12-22 07:27

I have the repository method inside my asp.net mvc web application, to automatically generate a unique sequence number called Tag:-

public void InsertOrUpdat         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-22 07:46

    A complete solution to this problem would be to combine the use of an auto incrementing column and computed column.

    The table would look something like this:

    CREATE TABLE [dbo].[somedata](
        [id] [bigint] IDENTITY(1,1) NOT NULL,
        [reference] [varchar](50) NULL,
        [STag]  AS ('S'+CONVERT([varchar](19),[id],(0))),
        CONSTRAINT [PK_somedata] PRIMARY KEY CLUSTERED ([id] ASC)
    )   
    

    With a mapping:

    public class SomeDataMap : EntityTypeConfiguration
    {
        public SomeDataMap()
        {
            // Primary Key
            this.HasKey(t => t.id);
    
            // Properties
            this.Property(t => t.id)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
    
            this.Property(t => t.reference)
                .HasMaxLength(50);
    
            this.Property(t => t.STag)
                .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
        }
    }
    

提交回复
热议问题