我想知道在使用存储库模式时如何正确处理复杂对象图的急切加载问题。我猜这不是 ORM 特定的问题。
第一次尝试:
public interface IProductRepository : IRepository<Product>
{
Product GetById(int id);
IProductRepository WithCustomers();
}
这可以正常工作,但这将涉及一直重复自己(在任何地方的存储库实现中编写自定义的“With”方法)。
下一个方法:
public interface IRepository<T> where T : IAggregateRoot
{
...
void With(Expression<Func<T, object>> propToExpand);
}
With
方法会将一个项目添加到私有集合中,稍后将使用该项目来找出在检索必要的实体时应该立即加载哪些道具。
这种工作很好。但我不喜欢用法:
productRepository.With(x=>x.Customer);
productRepository.With(x=>x.Price);
productRepository.With(x=>x.Manufacturer);
var product = productRepository.GetById(id);
基本上 - 问题是没有链接。我希望它是这样的:
var product = productRepository
.With(x=>x.Customer)
.With(x=>x.Price)
.With(x=>x.Manufacturer)
.GetById(id);
我无法做到这一点。即使我可以 - 我不确定该解决方案是否优雅。
这导致我认为我错过了一些基本的东西(任何地方都没有例子)。有不同的方法来处理这个吗?什么是最佳实践?