Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrency when deleting object in Entity Framework

I'm developing a web app using the entity framework. I load a list of objects and bind it to a repeater to show a summary of all the items. The user may click an edit icon or a delete icon for each item in the repeater.

Example:

Item 1 | Edit | Delete

Item 2 | Edit | Delete

...

Editing works fine when using a rowversion column for concurrency because the record is loaded and the values for the ID and rowversion column are persisted in hidden form fields. These "original" values are then available to use later when doing the update.

However, if the user clicks Delete for a record, I load the object from the database, call DeleteObject(), then call SaveChanges(). The problem with this is that when I load the record, it gets the latest rowversion value, so any concurrency checking is rendered useless.

How can I ensure that concurrency checking takes place when deleting a record?

like image 620
DCNYAM Avatar asked Nov 02 '25 08:11

DCNYAM


1 Answers

Actually you do not have to load the object from the database, if you want to delete it.

Instead, create an ObjectContext, attach your ObjectToDelete to that context via Attach(), then DeleteObject() and SaveChanges(). Thus you would be able to receive an exception about concurrency.

like image 98
Andreas H. Avatar answered Nov 05 '25 10:11

Andreas H.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!