I have a program that creates a unique key for a database. However I get an error that I am trying to write duplicate data to the database. How can I fix this?

Code:

private string GenerateScanID()
    {
        string scanID;

        scanID = "SC-" + DateTime.Today.Day + "-" + DateTime.Today.Month + "-" + DateTime.Today.Year + "-" +
                 DateTime.Now.ToString("hh-mm-ss.ffff");

        return scanID;
    }

Sample output:
SC-10-6-2015-09-21-34.1139-0
SC-10-6-2015-09-21-34.1139-1
SC-10-6-2015-09-21-34.1139-10

This ID generator depends on enough time elapsing between calls. I can see that running this kind of code in a fast loop could make duplicates:

for (int i = 0; i < 10; i++) {
    Console.WriteLine (DateTime.Now.ToString ("hh-mm-ss.ffff"));
}

Output:

05-16-12.2358
05-16-12.2779
05-16-12.2780 // <- Many duplicates are created.
05-16-12.2780
05-16-12.2780
05-16-12.2780
05-16-12.2780
05-16-12.2780
05-16-12.2780
05-16-12.2781

It could also be a problem elsewhere. If you can guarantee enough time has passed between calls, and it's impossible to generate duplicate IDs (like my code above), then it could be the way that the IDs are written to the database. They may be generated only once, but written twice.

That code snippet has nothing to do with the database insertion or how that scanID is being used. Can you post that up?

Databases can generate their own unique keys. Any reason why you can't do this? Sounds like you are making hard work for yourself.

If you really do want to generate unique keys yourself though then try a Guid eg:

private static string GenerateScanID()
{
    return Guid.NewGuid().ToString();
}

Second what DaveAmour suggests, used a GUID. They are like 99.9% unique (or something along those lines). While I never did find the exact logic behind how they are produced, I do know that time is factored into it.

Using time itself probably isn't the best idea because multiple piece of code and work very quick. For instance at my work, our logging has a similar TimeStamp to yours, we can produce multiple lines that all contain the same TimeStamp

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.