I am working on an application in which have different repositories for different entities and now i have to put search logic, hence i am confused where should i put my search logic, should i create a new repository for search or should i put the logic in the existing repository, and if i should put in some existing repository the which one is it.
the repositories are listed below
public class VendorRepository
{
}
public class ProductRepository
{
}
Public Class ProductBatchRepository
{
}
It depends on your logic and how "important" are every entity. For example, if you had the entities User and Address you could have UserRepository and AddressRepository. But only UserService, with methods like addAddress(User user, Address address)...
Repository should be per Aggregate root and not table. It means - if entity shouldn't live alone (i.e. - if you have a Registrant that participates in particular Registration ) - it's just an entity, it doesn't need a repository, it should be updated/created/retrieved through repository of aggregate root it belongs.
As the repository is an abstraction, it should always return whatever the layer above wants to work with, which in most cases are domain entities, i.e., the objects which will encapsulate the logic in your business code.
The Repository pattern allows you to easily test your application with unit tests. Remember that unit tests only test your code, not infrastructure, so the repository abstractions make it easier to achieve that goal.
Why not a base repository? Something like this:
public class GenericRepository<T>
{
protected IDbSet<T> Query<T>()
{
return myContext.GetDbSet<T>();
}
public IEnumerable<T> Where<T>(Expression<Func<T, bool>> predicate)
{
return Query<T>().Where(predicate).ToList();
}
...
}
and then the repositories:
public class ProductRepository : GenericRepository<Product>
{
}
public class VendorRepository : GenericRepository<Vendor>
{
}
Alternative approach that I like to use...
...you could seperate commands from queries. Your commands would use the underlying domain model and repositories (as you have it now?); while your queries could use another technology; for example; query the database directly using entity framework code first.
This way you have all the flexibility of querying (using LINQ) and bypassing layers that don't add value to query purposes, and design the return types specifically for your clients. You can even use database views if that would make it easier to query.
I would create methods for searching every entity in respective repository and create another class that would call all of them to search everything and transform the results in the desirable shape ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With