Duplicate Key on Save with MySQL.Data.Client

I updated my platform to use v5.0 of Servicestack. I believe in doing so, I ended up upgrading a number of packages, and I believe as a result of the updates, I think I managed to resolve the dependencies in the end, but I think I had to add the oracle MySQL.Data (6.9.10) package to do so. Hopefully that was the correct move. This may be related to the following issue:

Package-update-needed-for-ormlite-sqlclient

Today, for the first time, I saw the following error message:

MySql.Data.MySqlClient.MySqlException: Duplicate entry ‘123…’ for key 'PRIMARY

This was the result of multiple “Saves” (x2) on the same entity in quick succession (the first of which was the first time the entity was saved). Both use a microservice method call where the code looks like this:

        using (var db = DbFactory.Open())
        {
            CheckTableExistsAndInitialize<Activity>(db);
            db.Save<Activity>(request.Activity);
            return db.SingleById<Activity>(request.Activity.ID);
        }

I wondered if this is somehow due to the fact that the Save internally checks record existence and then either chooses to INSERT or UPDATE, and somehow the dual saves were causing a race condition where both saves attempted an insert. Is this possible? and/or do you have any thoughts on this ?

The strange thing is that while this code sits in a micro service method which is called from a consuming application, the two subsequent calls to the micro service are made from a single thread in serial fashion. Which means that the first micro service method call should have been completed before the second is made.

Best Regards

You can look at the ServiceStack.MySql NuGet Dependencies to see what MySql.Data version it’s built with (for .NET Framework it’s v6.9.10).

Yeah potentially, an Upsert would handle the conflict on the server but it’s currently not implemented in OrmLite atm.
In the latest release notes we’ve added support for Conflict Resolution where you can choose to ignore the 2nd duplicate entry on Insert, but would require using Insert or Update APIs.

1 Like

Thanks for the feedback, much appreciated.