The selection of database primary keys has always been a headache. there have been a lot of discussions in the garden. including this small discussion on Database primary key selection policy (original) and the primary key design of this database. These two articles are both excellent. Article Basically, I made some comparisons on several selection strategies. On this basis, I also had some rough understandings. In contrast, the custom primary key is still a good choice, however, there are some considerations in the generation method, such as concurrency issues, therefore, it is not as good to store the numbers in the database in the "MAX + 1" and "Homemade plus 1" solutions, based on the ideas provided by these two solutions, I wrote such a C # primary key generator:
1. To avoid thread conflicts, the single-piece mode is used to generate a primary key and store the previous primary key to avoid duplicate primary keys.
2. The field type adopts the fixed-length struct type, such as char (20). Different prefixes can be added before the generated string, such as the table prefix or other meaningful identifiers.
3. Convert the hexadecimal type into a letter to make the last length smaller.
For more information, see: 1 Using System;
2 Using System. Collections. Generic;
3 Using System. text;
4
5 Namespace GB. Core
6 {
7 /// <Summary>
8 /// Powered by shujia, matin0728@gmail.com, 2017362131
9 /// </Summary>
10 Public Class Identitygenerator
11 {
12 Static Long Lastidentity = 0 ;
13 Static Identitygenerator o = New Identitygenerator ();
14 Public Static Identitygenerator instance
15 {
16 Get
17 {
18 If (O ! = Null )
19 Return O;
20 Else
21 Return New Identitygenerator ();
22 }
23 }
24 Public String Nextidentity ()
25 {
26 Long Idint = Datetime. Now. ticks - New Datetime ( 2000 , 11 , 1 ). Ticks;
27
28 While (Lastidentity > = Idint)
29 {
30 Idint ++ ;
31 }
32 Lastidentity = Idint;
33
34 Return Convert. tostring (idint, 16 );
35 }
36 }
37 }
38