Benefit of using Unit of Work and Repository Patterns with Entity Framework

后端 未结 2 1746
醉酒成梦
醉酒成梦 2020-12-24 01:19

According to MSDN, DbContext is defined as:

Represents a combination of the Unit-Of-Work and Repository patterns and enables you to que

2条回答
  •  醉梦人生
    2020-12-24 01:51

    Yes, DbContext represents a Unit of Work and DbSet represents a Repository, but some people will create a layer of abstraction over them. Here are some reasons people might do so:

    • Maybe they don't want their project tightly coupled to Entity Framework and its architecture. So, they hide Entity Framework behind those abstractions so they can substitute Entity Framework for any other ORM without any modification to the interface of the data access layer.
    • They use repositories to make it clear which operations are allowed for certain entities. (For example, CustomerRepository might allow adding and updating customers but not deleting them). On the other hand, it enables a client developer to easily recognize available operations for certain entities. In other words, they create repositories with naming conventions and interfaces that are compatible with the domain language.
    • Moving database-related operations to repositories allows you to intercept those operations and perform logging, performance tuning or any other operation you want.
    • Some do it to make testing easier. Say I have an ICustomerRepository interface with three methods. Then I can easily mock that up instead of mocking an IDbSet with too many methods.
    • Finally, there are many who do not create an abstraction over DbContext and DbSet. They just use them directly and it is perfectly valid to do so.

提交回复
热议问题