-1
  1. I have one class in c# which contains the referral Property. like below

    class Abc { public string referral {get;set;} }

  2. When I will use migration I will be generated as a column in the table (in SQL).

  3. I want the value of that filed to be unique in the whole system.
  4. And the length should be 20 without any space.

Note: I am adding value from UI to value should be known to me It shouldn't any random string.

Is there any way to do that?

5 Answers5

1

You can use

string guid = System.Guid.NewGuid().ToString();

to generate unique strings and then just store them in Data base and of cause you will need to customize EF migration script

Sergey K
  • 4,071
  • 2
  • 23
  • 34
1
class Abc {
[Key]
[StringLength(20)]
      public string referral {get;set;}
    }`

if you are inputing the string from the ui this will ensure that the string is unique for all your db entries.

James Njoroge
  • 11
  • 1
  • 1
0

Try this:

class Abc 
{
  [Index(IsUnique = true), Required, MaxLength(20)]
  public string referral {get;set;}
}

Khyzer
  • 13
  • 1
  • 4
0

The way to create unique identifiers in client code is using System.Guid, but they are 32 characters long, even with the hyphens removed.

This is a nice way to truncate a GUID, but it still uses 22 characters.

If you need to use something shorter, then your going to increase the risk of collisions, but this gives a 1 in 7 × 10^32 which is probably adequate:

string Generate20Characters()
{
    string characters = "abcderfhijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    var random = new Random();
    return string.Join("", Enumerable.Repeat(chars, 20).Select(s => s[random.Next(s.Length)]));
}
Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35
0

This answer here gives a detailed explanation of creating short unique strings

A simplest solution would be to :

// Specify characters to incclude in the unqiue Id
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
// Create char array of 20 length which you need
var charArray = new char[20];
var random = new Random();

for (int i = 0; i < charArray.Length; i++)
{
    charArray[i] = chars[random.Next(chars.Length)];
}

var uniqueString = new String(charArray);

Another easier and simple approach would have been to Base64 encode a Guid which would result in a 24 character unique string which would end with == which you can trim to further shorten it to 22.

var newId = Guid.NewGuid();
var uniqueString = Convert.ToBase64String(newId.ToByteArray());

But as your length requirement is 20 you can stick to the first one.

Shahid Manzoor Bhat
  • 1,307
  • 1
  • 13
  • 32