I have a client who's been running a program of mine for a couple of years now who started getting strange errors. My application throws exceptions with this in it:
Cannot insert duplicate key in object
Since I didn't touch the code in literally years, this confused me a lot. And it only happened sometimes.
After A LOT of debugging and pulling out my hair, I figured out what is happening.
In the code that adds items to the database, I call session.SaveOrUpdate.
I can't recall a specific reason i chose this over the expected session.Save method, but let's continue. (i am changing this for the client's code though).
So what seems to be happening is that the SaveOrUpdate is re-using existing object's ID's and completely overriding the existing item. My code throws an error, but the new item is saved to the DB and there is no trace of the original record any longer. In my nhibernate mapping documents I am using the hilo generator for object IDs.
I am guessing this is only happening because there are now enough items in the DB to make the IDs restart or something, i don't know. I do have an audit table that has/had A LOT of records in it. 10,000's. But i truncated that table to make backups smaller. (could this have causes this problem).
I'm trying to find out if anyone can conclusively state if the SaveOrUpdate does for some reason re-use existing IDs or why changing the call to just Save works now. If this is a known issue i will sleep easy, if not, i need to further debug to see if there isn't still some situation where my client will lose data.
My code is running Nhibernate 3.3.3.4000, which was the latest code when i wrote this app.
Update 1
Session.Save is also re-using ID's.
I keep getting duplicate key errors, when inserting new records. But not every time, only some times. So it's quite random, which makes it hard to debug.