I have the following way of adding or updating an object of type Item for some user. This method is part of the Service class, a new instance of which is created for each request.
public async Task SaveItem(int userId, string name) { var item = await _context.Items.Where(i => i.UserId == userId).SingleOrDefaultAsync(); if (item == null) { item = new Item { UserId = userId, Name = name }; _context.Items.Add(item); } else { item.Name = name; _context.Entry(item).State = System.Data.Entity.EntityState.Modified; } await _context.SaveChangesAsync(); }
The problem is that two simultaneous requests can create two elements for the same user, which is invalid. For me, this looks like a fairly common piece of code, and I wonder what is the standard way to solve this concurrency problem.
source share