'.NET Core EF Multithreading

I'm calling an .NET Core API endpoint parallel (10x) from a client, where I try to check if an object exists in the database and create it if not. My problem is that the query code will be executed 10 times and it will create the same record 10 times:

Query 1 Query 2 ... Query 10 Insert 1 Insert 2 ... Insert 10

My question is what are the best practices to prevent such events?
I've tried to change DI DBContext from Scoped to Transient, but no luck. Do I have to create some sort of semaphore or locking mechanism?

Thanks in advance



Solution 1:[1]

your question seems to be a bit moot as in a real life application, the scenario you are describing would not happen. You may have one Task to create and others consuming if it exists, but surely not 10 parallel inserts of the same item to a table.

As Shak Sam pointed out, you could use an index with .IsUnique() to ensure that certain object may only exist once. Or, if this is supposed to be a static object in the table, say a root item for a linked list, then you could always try hard coding the Key for that object.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kieran Foot