Repository and Unit of Work patterns - How to save changes

后端 未结 5 1796
旧巷少年郎
旧巷少年郎 2021-01-30 05:28

I\'m struggling to understand the relationship between the Repository and Unit of Work patterns despite this kind of question being asked so many times. Essentially I still don\

5条回答
  •  天命终不由人
    2021-01-30 06:01

    Repository can work without Unit Of Work, so it can also have Save method.

    public interface IRepository
    {
         T Get(int id);
         void Add(T entity);
         void Update(T entity);
         void Remove(T entity);
         void Save();
    }
    

    Unit Of Work is used when you have multiple repositories (may have different data context). It keeps track of all changes in a transaction until you call Commit method to persist all changes to database(file in this case).

    So, when you call Add/Update/Remove in the Repository, it only changes the status of the entity, mark it as Added, Removed or Dirty... When you call Commit, Unit Of Work will loop through repositories and perform actual persistence:

    • If repositories share the same data context, the Unit Of Work can work directly with the data context for higher performance(open and write file in this case).

    • If repositories have different data context(different databases or files), the Unit Of Work will call each repository's Save method in a same TransactionScope.

提交回复
热议问题