3

I am new to Repository pattern.

When I am managing the CRUD operations of several entities (like: customers, orders etc) then its fine. I am making an interface, I am making a Generic repository. And that serves my purpose, because CRUD operation is common for them.

My question is:

When the duties of several entities are totally different, there is no common method between them, in this case what should I do? Should I increase the number of interfaces and repositories for those specific purposes? Or is there any better solution in terms of best practices?

Amit Joshi
  • 15,448
  • 21
  • 77
  • 141

1 Answers1

3

How should I manage Generic Repository Pattern when the works of different entities are pretty much different?

This is the core problem with Generic Repository pattern; that is why it is considered an anti-pattern.

I read this here:

No matter what clever mechanism I tried, I always ended up at the same problem: a repository is a part of the domain being modeled, and that domain is not generic. Not every entity can be deleted, not every entity can be added, not every entity has a repository. Queries vary wildly; the repository API becomes as unique as the entity itself.

Why generic repository is anti-pattern?

  1. A repository is a part of the domain being modeled, and that domain is not generic.
    • Not every entity can be deleted.
    • Not every entity can be added
    • Not every entity has a repository.
    • Queries vary wildly; the repository API becomes as unique as the entity itself.
    • For GetById(), identifier types may be different.
    • Updating specific fields (DML) not possible.
  2. Generic query mechanism is the responsibility of an ORM.
    • Most of the ORMs expose an implementation that closely resemble with Generic Repository.
    • Repositories should be implementing the SPECIFIC queries for entities by using the generic query mechanism exposed by ORM.
  3. Working with composite keys is not possible.
  4. It leaks DAL logic in Services anyway.
    • Predicate criteria if you accept as parameter needs to be provided from Service layer. If this is ORM specific class, it leaks ORM into Services.

I suggest you read these (1, 2, 3, 4, 5) articles explaining why generic repository is an anit-pattern.

Better approach is:

  1. Skip the Generic Repository. Implement concrete repositories.
  2. Use Generic Repository as abstract base repository. Derive all concrete repositories from it.

In any case, do not expose generic repository to calling code. Also, do not expose IQueryable from concrete repositories.

Amit Joshi
  • 15,448
  • 21
  • 77
  • 141
  • Please refer [this](https://stackoverflow.com/a/45460483/5779732) sample code with C# and Dapper. Note that `BaseRepository` class in example is `abstract` class. You have to further write concrete repositories over it. – Amit Joshi Apr 23 '18 at 06:48