I didn’t understand why I would want to use the Unit of Work pattern before I ran into this. I had a ManagerBase class that had an IRepository. (The managers implement ManagerBase which have a private Repository that follows Juans approach http://geekswithblogs.net/JuansAndZeros/archive/2012/10/03/building-a-repository-pattern-against-ef-5-model-first.aspx)The Repository had the context and saveChanges method. This means that each “Manager” I had, contained a different instance of the context. This all worked well until I tried to save into a linking table. This code shows how I tried to update the users assigned to a certain Layout. Layout has a ICollection<UserProfile> property of UserProfiles as generated by the EF Power Tools from our database.
var assignedUserProfiles = this._userProfileManager.GetAll().Where(u => assignedList.Contains(u.UserId));
layoutMatch.UserProfiles = assignedUserProfiles.ToList();
this._layoutManager.Update(layoutMatch, layoutMatch.LayoutId);
It creates a new record in UserProfiles and in the LayoutUsers, even through the UserProfile object in assignedUserProfiles had the UserId (PK) set.
The state was always "Added" when Debugging the Repository, before the SavedChanges call.
I believe this is because the userProfileManager and the layoutManager have different contexts.
This StackOverflow question shows the same problem and Ladislav Mrnka mentions using a Unit of Work pattern to handle this problem, which links to this question.
One last link: http://codereview.stackexchange.com/questions/14226/generic-repository-and-unit-of-work-code
Once I moved the context into the ManagerBase and I pass in that same context to both Repositories, the save worked as expected. So I now basically have a UnitOfWork and Repository pattern after all, we just call it a “Manager” instead/