Question
I am interested in understanding how the Unit of Work concept relates to Entity Framework, and how it can be customized to suit certain scenarios? I have some experience with Entity Framework, though I have not been involved in any projects that made use of Unit of Work. Could you please provide an overview of how Unit of Work works with Entity Framework?
Answer
Unit of Work is about executing a number of different tasks as a single action and is conceptually related to the effective implementation of the Repository Design Pattern.
Suppose you’re creating an application to handle customers and orders. You could have a repository to handle everything related to Customers, complete with its own dbcontext. And another for the Orders, also with its own dbcontext.
When you have these 2 repositories, it’s possible that a single operation might span both repositories. However, having two dbcontexts is error prone. One can fail and the other succeed, leaving your database in an inconsistent state. So Unit of Work tries to solve this, pretty much by using a single generic repository that can handle all operations across the 2+ repositories.