ASP.NET | Entity Framework Race Status

I have a web application where users are allowed to love objects. Each item has the property of everything that he received.

The problem arises when many users like the same element at the same time, then I get the wrong values ​​in SQL (caused by the race condition).

As a temporary solution, I created a workflow in the controller’s constructor, which works against the queue, when it receives a request like / dislike, I execute a queue with this request. The workflow deactivates the values ​​and updates the dictionary that maps itemid to totalcount.

The workflow then updates the database once every minute with the result.

Side question: context.SaveChanges()to save only what has changed in the object? Or does it save all the properties of objects?

I have a feeling that this solution is not right, what is the best way to deal with such a problem?

+4
source share
2 answers

You can use RepeatableReadthe scope of a transaction transaction when reading and writing occurs:

using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = IsolationLevel.RepeatableRead }))
{
    ...
    context.SaveChanges();
    scope.Complete();
}

Entity Framework entity fields are modified and generate SQL code to update only those that have changed. You can specify that you want to update only one property of an object and ignore other changes:

context.Entry(entity).State = EntityState.Unchanged;
context.Entry(entity)
        .Property(c => c.entityField).IsModified = true;

It can also be useful when you attach an object to a context:

context.Attach(entity);
context.Entry(entity)
        .Property(c => c.entityField).IsModified = true;

Because it Attachputs objects and its properties in context in state Unchanged.

+1
source

concurrency ExecuteSqlCommand:

string sql = "UPDATE Table SET LikeCount = LikeCount+1 WHERE Id={0}";
using (var context = new BloggingContext()) 
{ 
    context.Database.ExecuteSqlCommand( sql, new SqlParameter("@Id", id)); 
}
0

Source: https://habr.com/ru/post/1650202/


All Articles