0

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?

2
  • 1
    The problem is your whole approach. If you want an ID that is unique in the table/database, you should ask the database engine to provide one for you. Commented Feb 11, 2014 at 19:00
  • maybe it will work but i need to fix this code and not to write new one. Commented Feb 11, 2014 at 19:39

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

i know that i generate it with math random, i cannot do it with 0 because i have user 0 i need all the time new users but from 0-infinity with no holes. i cannot change the DB it's not mine. but i think it will work what your are saying. Thx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.