I have an API Endpoint that gets a lot of competitive requests. The code below periodically gives an error:
Violation of PRIMARY KEY constraint 'PK_Visitors'. Cannot insert duplicate key in object 'dbo.Visitors'.
var entityDB = await db.Visitors.FindAsync(entity.Id);
if (entityDB is not null)
{
entityDB.Url = entity.Url;
entityDB.Source = entity.Source;
// etc...
}
else
{
db.Visitors.Add(entity);
}
await db.SaveChangesAsync();
I understand very well that the problem occurs when the first request has started adding a record, but the second request in the FindAsync
line does not yet see the new record and goes the same way adding a new one, which causes a primary key conflict.
Are there ways to avoid this problem with EF Core 7? I tried using transactions, but that didn't solve the problem.
- The primary key is not generated on the SQL side, but in a separate external function. Therefore, for duplicate keys, it is assumed that the record will be updated.