Reputation: 1097
I'm using Silverlight and I'm trying to get the ID for my new user from my database.
This is how I'm doing it:
Random r = new Random();
int id = r.Next(1000,2000) * 10;
query = "SELECT MAX(ParticipantID) FROM Participant";
SqlCommand cmd2 = new SqlCommand(query, SqlCon);
try
{
SqlCon.Open();
id = (int)cmd2.ExecuteScalar();
}
catch { logger.Error("Add: sqlConnectionError"); }
finally { SqlCon.Close(); }
My problem is that sometimes I get the the id
from the random math and not from my database.
The problem will appear in the SqlCon.Open();
or in id = (int)cmd2.ExecuteScalar();
line?
Is there a way that if it's not getting the id from the database it will try again?
Let's say try 100 time until the id is different then before?
How can I do it? I can not do it recursively.
Is there a way with a loop?
Upvotes: 0
Views: 78
Reputation: 73502
i get the the "id" from the random math and not from my DB
It is because you're generating it randomly using this
int id = r.Next(1000,2000) * 10;
Why to initialize it with Random
in first place? initialize it with 0
.
int id = 0;
for (int i =0; i<100; i++)
{
id = ...;//Get value from DB
if(IsValidId(id))//validate the ID
{
break;
}
}
However it sounds like you should be using Auto-Increment
column; that's the better option if you're just looking for uniqueness.
Upvotes: 1