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?
- 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.
- 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.
- Working with composite keys is not possible.
- 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:
- Skip the Generic Repository. Implement concrete repositories.
- 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.