I am building an ASP Web API project, using SQL Server for storage, and Entity Framework to connect to it.
Several tables in the storage contain unique constraints to enforce uniqueness of values in them. Before adding values to these tables, my application checks to ensure that the values do not exist.
The application is built so that one DbContext exists per request. It has occurred to me, however, that two requests could attempt to insert the same value into the table. Request A would check for the existence of the value in the table, as does Request B. Both ascertain that the value requires adding, and add it to the DbSet. When SaveChanges is called, one request will succeed, and one will fail due to the unique constraint failing it.
How can these sort of issues be resolved with Entity Framework? I am planning to create stored procedures to retrieve or create the values, which I think should solve it (the stored procedures guaranteeing the atomicity), but I would be keener on a way to solve this solely with Entity Framework itself. I think I like the idea of queueing up a load of actions that only get executed when DbContext.SaveChanges() is called, but obviously the stored procedure solution would mean that database interactions would take place before SaveChanges().