I have a simple situation but I am afraid that it will throw exceptions sometimes. Case: We have X users in the application and these users can search for some data. If any data will be found then that data should be incremented on one of its fields. For example:
class Book {
public int Id {get; set;}
public string Name {get; set;}
public int FoundCounter {get; set;}
}
and if we will find a book then we should increment "FoundCounter" field.
It's very easy but if we have X users and these users are using search then we can situation when a few users will find exactly the same book and then all threads will want to update the same record.
I'm afraid that then I will get an exception. I use C# and EF Core.
Is there any way to do it safely?
Best Regards, Krzysztof.
CodePudding user response:
Sorry I can't post comments because my reputation is too low. You might want to consider the question some more. Can a book be found multiple times by the same user? If you do a search does it return many book records? These are scenarios you need to consider and it will make the answer more complex. Let's say we just return a list of books and then select 1 book in the list, then we will increase the "FoundCounter".
When you get the record you can increment the count and then return the book record.
public async Task<Book> ReturnBook(bookId Id)
{
using (var context = new DataContext())
{
var book = await context.Books.FirstOrDefault(x => x.Id == bookId);
book.FoundCounter
context.SaveChangesAsync();
return book;
}
}
This will increase your FoundCounter each time a record is retrieved. Again, there are more questions that need answered for this but this is the most basic example of what I think you might be asking.
CodePudding user response:
You can take care of the concurrency situation in EF core by using concurrency tokens. This site has a good example and description. https://www.learnentityframeworkcore.com/concurrency