I am having difficulty with the following code which is inside a static method of a non-static class.
int iRand;
int rand;
rand = new Random((int)DateTime.Now.Ticks);
iRand = rand.Next(50000);
The iRand number, along with some other values, are being inserted into a new row of an Access MDB table via OLEDB. The iRand number is being inserted into a field that is part of the primary key, and the insert attempt is throwing the following exception even though the iRand number is supposed to be random:
System.Data.OleDb.OleDbException: The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again.
Could the fact the method is static be making the iRand number stay the same, for some reason?
You should not be using Random Numbers for primary keys! First of all, yes, there is a chance of collision, in your case, n/50000,where n is the number of previously created numbers. (Thanks, Guffa)
Secondly, why not use sequential values? i.e. first begin with 1, 2, 3, etc. No collision, guaranteed unique.
On the other hand, I have come across the problem of random numbers being “stuck” in a cycle, and this occurred because
Randomis not thread-safe. This is how I handled it : C# Random Number Generator getting stuck in a cycleAlso, why not add some logging code so that you can examine the random numbers being output, and check how much data is inside the user’s DB already? (Although I am pretty sure you did that already)