Transactions in the Repository Pattern

后端 未结 6 881
小鲜肉
小鲜肉 2020-12-12 18:07

How do I encapsulate the saving of more than one entity in a transactional manner using the repository pattern? For example, what if I wanted to add an order and update the

6条回答
  •  甜味超标
    2020-12-12 18:22

    How do I encapsulate the saving of more than one entity in a transactional manner using the repository pattern? For example, what if I wanted to add an order and update the customer status based on that order creation, but only do so if the order completed successfully? Keep in mind that for this example, orders are not a collection inside the customer. They are their own entity.

    Its not a responsibility of the repository, its usually something done at a higher level. Although you said your not interested in specific technologies I think its worth tying down the solutions, for example when using NHibernate with a Web app you'd probably consider using session-per request.

    So if you can manage transactions at a higher level then my two options would be:

    1. Upfront check - For example in a service co-ordinating the behavior decide if you want to proceed by asking the Order/Customer, if either say they don't then don't even try to update either of them.
    2. Rollback - Just proceed updating the Customer/Order and if things fail part way through rollback the database transaction.

    If you go for the second option then the question is what happens to the in-memory objects, your Customer might be left in an inconsistent state. If that matters, and I work in scenarios where it doesn't as the object was only loaded in for that request, then I'd be considering the upfront check if its possible because its a lot easier than the alternatives (rolling back the in-memory changes or reloading the objects).

提交回复
热议问题