Is unit of work a good pattern for transactions that will auto generate new objects (auto_increment id)?

拥有回忆 提交于 2020-01-14 00:33:50

问题


From the unit of work pattern i uderstand a method of doing typic transactions based on some domain repostiries (using a repository per domain object) . Example : after defining some repository objects in the UoW object , commit those repositories based on theyr state .

Also the repositories should not contain any transaction logic .

What happens when an insert() leads to a creation of a new object (auto generated id) that later on is needed by another object in the same transaction ?

Unit of work does not seem to work for this case . There could be even more specific and complex transaction where objects are generated when the UoW commit is ran .

How should the transactions be treated in this case ?


回答1:


Usually ORMs like NHibernate or EntityFramework know how to handle the order of calls to DB. E.g. NHibernate's inverse is used in order to specify who is responsible for bidirectional relationship.

If you develop your own DataAccessLayer/ORM it is your responsibility to specify the invocation order. The simplest solution is 'Add all new entities' => 'Delete all deleted entities' => 'Update all dirty entities'.

Once an entity is added to DB you can retrieve as a result its @@IDENTITY/ SCOPE_IDENTITY and then update its Id using any appropriate solution.



来源:https://stackoverflow.com/questions/20622203/is-unit-of-work-a-good-pattern-for-transactions-that-will-auto-generate-new-obje

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