I have the following scenario:
A business logic function that uses ef6 checks if a record already exists. If the record does not exists, it is inserted on the database.
Something like this
if (!product.Skus.Any(s => s.SkuCodeGroup == productInfo.SkuCodeGroup && s.SkuCode == productInfo.SkuCode))
AddProductSku();
I have multiple threads calling this business logic function. What happens is:
If the function is called simultaneous with the same parameters, both instances checks if the record exists - and it does not exists. So both instances inserts the same record.
When context.SaveChanges() is called on the first instance, all goes ok. But the second SaveChanges() throws an exception because the record already exists (there is an unique index on the database).
How can I implement this to avoid the exception?
I solved it by using a lock {}, but it creates a bottleneck that i don't want.
Thank you.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…