2

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 ?

Geo C.
  • 755
  • 6
  • 18

1 Answers1

2

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.

Ilya Palkin
  • 14,687
  • 2
  • 23
  • 36
  • How can you add to the db a row that has foreign key constraints ? Your solution seems to make a temporary referencerence to a non existing ID . This workaround does not sound good . – Geo C. Dec 18 '13 at 21:40
  • Anyway your solution is not good for complex, nested auto_generated objects . How many persist calls you should do on the dirty/new objects ? This might seem impossible and not a good solution for complex transactions . – Geo C. Dec 18 '13 at 21:51
  • 1
    @Geo C. I do not support 'temporary reference to a non existing ID' at all. If row has foreign key constraints then these constraint should be added before (e.g. correct usage of NHibernates inverse solves it). So, **first you add all referenced entities, then you add row that has foreign keys to those entities**. If one knows order of calls to DB then it is possible to form rules for code. – Ilya Palkin Dec 19 '13 at 08:35
  • @GeoC. "How many persist calls you should do on the dirty/new objects ?" I do one call per new, one call per deleted, one call per dirty entity. But you have many options. **First** - every `INSERT`, `UPDATE`, `DELETE` is separate call from your application to DB (in my case I used stored procedures for complex solution). **Second** - you can somehow combine generated SQL to reduce a number of calls to DB. **Third** - you can simply use any ORM and configure it. – Ilya Palkin Dec 19 '13 at 08:53