From many articles and answers on DDD Repository pattern, I got the feeling that a Repository should only CURD an Entity (Aggregate Root) as a whole.
Following this convention, we always need to query the database to get all required data to construct an Entity. Following is an example implementation when you want two properties of the Entity:
class ProductInfoDto
{
public string ProductName {get;set;}
public decimal ProductPrice {get;set;}
}
class ProductRepository : IProductRepository
{
Product GetProduct(int productId)
{
//query database to fetch all data needed and create a Product
}
}
class ProductReportService : IProductReportService
{
IProductRepository _repo;
public ProductInfoDto GetProductInfo(int productId)
{
var product = _repo.GetProduct(productId);
return new ProductInfoDto(product.Name, product.Price);
}
}
Actually we can just query the database to get Name
and Price
and create ProductInfoDto
to improve query performance (since there are less data need to be fetched):
class ProductInfoDto
{
public string ProductName {get;set;}
public decimal ProductPrice {get;set;}
}
class ProductRepository : IProductRepository
{
ProductInfoDto GetProductInfo(int productId)
{
//query database to fetch product name and price
return new ProductInfoDto(productNameFromDb, productPriceFromDb);
}
}
class ProductReportService : IProductReportService
{
IProductRepository _repo;
public ProductInfoDto GetProductInfo(int productId)
{
var productInfo= _repo.GetProductInfo(productId);
return productInfo;
}
}
But this breaks the convention that Repository should only CURD an Entity (Aggregate Root) as a whole. This implementation does have drawbacks that will make the Repository fragmented and bloated with many methods and DTOs, as the business logic on the Entity becomes more and more complicated.
My major concern is the performance issue. What should I do to implement the Repository properly? Why?
UPDATE about bypassing the repository said by VoiceOfUnreason:
the option of bypassing the repository and fetching the information you need more directly.,
I think CQRS Query also uses Repository to fetch required data. And to follow the principle of *Persistence Ignorance, EFCore DbContext or ADO.NET should only be used in Repository to keep Query from affected by Persistence.