简体   繁体   中英

Violation of PRIMARY KEY constraint when published on Azure

ASP yields a Violation of PRIMARY KEY constraint on a specific ID. (I randomly generate the ID's in code, while checking they don't already exist in the database).

When I debug this code on my local machine (with the same Azure hosted database) everything works fine. When I publish my code on Azure I get the error. Strange thing is that the random ID, yielded by the error, does NOT exist in my database.

Code (I copy a list of medication with a new id & new schemeID):

        List<medication> l = db.medication.AsNoTracking().Where(x => x.scheme_ID == schemeID).ToList();
            foreach (medication m in l) {
                int id = generateUniqueMedicationID();
                m.ID = id;
                m.scheme_ID = newSchemeID;
                db.medication.Add(m);
            }
        db.SaveChanges();

generateUniqueMedicationID() method:

    private int generateUniqueMedicationID()
    {
        bool stop = true;
        int id = -1;
        while (stop)
        {
            Random r = new Random();
            id = r.Next(100000000, 1000000000);
            if (!db.medication.Any(o => o.ID == id)) stop = false;
        }
        return id;
    }

The C# 'Random' method, isn't a true random number generator. As Microsoft puts it, it is a " pseudo-random number generator".

This MSDN article[ https://msdn.microsoft.com/en-us/library/system.random(v=vs.110).aspx] says:

Pseudo-random numbers are chosen with equal probability from a finite set of numbers. The chosen numbers are not completely random because a mathematical algorithm is used to select them, .....

To generate a cryptographically secure random number, such as one that's suitable for creating a random password, use the RNGCryptoServiceProvider class or derive a class from System.Security.Cryptography.RandomNumberGenerator.

In simple words, the numbers get repeated after a certain interval.

The best way to have non-sequential ID values, if you are using SQL server 2012 (or higher), is to change your ID column and use the uniqueidentifier type, which generates GUID and you should let your DB engine to create and assign the value, not your C# code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM