What is a good method to determine when an entities data has been changed on the database?

心已入冬 提交于 2019-12-24 08:58:42

问题


Say, using Entity Framework, I have retrieved an Entity from the database. Is there any way to check subsequently that the same specific Entity has changed in the database by another user?

The method I have used previously (in WinForm applications) was to:

  • Save Entity to the db
  • Add an entry to a Transactions table with the Entity type, Unique identifier, and datetime changed
  • When refreshing the same Entity, check for rows in the Transaction table subsequent to the current user's Save.
  • If an entry is found, act accordingly (reload Entity from database, block Editing, Save conflicts etc depending on why I am checking for a change).

The reasons I want to do this is to:

  • Avoid reloading an entire set of Entities and just refresh the Entities that have changed
  • Check for concurrency conflicts on Save
  • Resolve concurrency conflicts based when Editing began. To do this I need to make an entry in the Transactions table when a user begins editing and update the same Transaction table row when the user saves / cancels.

Does this method seem right? Are the reasons for doing this even correct at all? And perhaps there's already functionality to do this that I haven't been able to find?


回答1:


I wonder why you don't use one of the more standard ways of optimistic concurrency. EF has support for this. I think a separate Transactions table only adds complexity because you always have to explicitly maintain entries in that table while doing CRUD operations on the main entities. What happens when a user begins editing and creates a "locking" entry in the Transactions table, but then crashes? Wouldn't an exclusive lock on the record in the database be appropriate here (i.e. pessimistic locking).

You can also use this approach to check for intermediate changes, because you can execute a light query on the timestamp or version column.



来源:https://stackoverflow.com/questions/7279653/what-is-a-good-method-to-determine-when-an-entities-data-has-been-changed-on-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!