A self-written primary key generator

Source: Internet
Author: User
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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.