Darren Alfonso
Darren Alfonso

Reputation: 1390

SqlException: Violation of ****** constraint '******'. Cannot insert duplicate key in object '******'. The duplicate key value is ******

When trying to insert users into the AspNetUsers table using EF, I got the following error:

Microsoft.EntityFrameworkCore.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details.'

SqlException: Violation of ****** constraint '******'. Cannot insert duplicate key in object '******'. The duplicate key value is ******. The statement has been terminated.

That error is verbatim (it actually showed the asterisks). Before inserting the users, I explicitly deleted them, so I don't know why I'm getting this error.

Code to delete users

            foreach (var user in globalUsers)
            {
                if (rdb.Users.Any(u => u.Email == user.Email))
                {
                    var existingUserInDb = rdb.Users.First(u => u.Email == user.Email);
                    rdb.Users.Remove(existingUserInDb);
                    await rdb.SaveChangesAsync();
                }
            }

Code to add new users

            foreach (var gu in globalUsers)
            {
                rdb.Users.Add(gu);
                await rdb.SaveChangesAsync();
            }

Upvotes: 2

Views: 280

Answers (1)

Darren Alfonso
Darren Alfonso

Reputation: 1390

The issue was the following:

  • When adding the users, I had set the User IDs explicitly
  • We were using soft deletes, so deleting the existing user wasn't actually deleting it
  • ASP.NET/EF didn't read the soft delete, and so I was inserting another user that had the same User ID as the soft deleted user

I solved the issue by creating a new User ID when inserting the users.

        foreach (var gu in globalUsers)
        {
            gu.Id = Guid.NewGuid().ToString();
            rdb.Users.Add(gu);
            await rdb.SaveChangesAsync();
        }

Upvotes: 1

Related Questions