Not quite sure how to word this question but here it goes. I am working on a project where multiple client applications are accessing one data source through a WCF service. It may not be relevant but the WCF service is utilizing entity framework to access this data source. Whenever a client has queried a record for editing, I would like to prevent that same record from being edited by the rest of the clients till the first client has completed their update.
Correct me if I am wrong but I believe this is also known as synchronous and asynchronous data access.
My question is, what is the industry best practice to implement this functionality. Is there a way to control this from the database side (Using SQL) or must it be done through the client?
I have considered including a boolean 'EditMode' column for each table and simply setting it to true when it is being edited and check if that is set to true before allowing another client to access that record.
We can update records either in connected or disconnected scenarios. In the connected Scenario, we open the context, query for the entity, edit it, and call the SaveChanges method. In the Disconnected scenario, we already have the entity with use. Hence all we need to is to attach/add it to the context.
The AsNoTracking method tells Entity Framework to stop that additional work and so, it can improve the performance of your application. So, in theory, a query with AsNoTracking should perform better than without.
Entity Framework Core provides no support for pessimistic concurrency control.
Best practice is to use RowVersion and Optimistic locking.
Optimistic Concurrency Patterns explained.
If using Code first, then include a field in your POCO.
public virtual byte[] RowVersion { get; set; }
EF will add a Timestamp/RowVersion property to your table. It will be checked during Update. And automatically updated by the DB when changed.
EDIT: to better explain.
What EF is looking for is properties that are concurrency fields so you can actually control the concurrency with one or more fields.
entity.Property(p => p.RowVersion).IsConcurrencyToken()
when performing an update or delete you catch the defined exception
catch (DbUpdateConcurrencyException ex)
EF treats the RowVersion as a concurrency token. This is the Generally used approach. Since SQLServer will automatically update this field type for you. So very fast and easy. But you can tell EF a property is a concurrency token explicitly and have more than one.
So EF should add properties to the where clause for updates and deletes to make sure the record didn't change since accessed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With