Reputation: 1390
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
Reputation: 1390
The issue was the following:
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