How to create a collection of Expression<Func<T, TRelated>>?
I have a repository with the following method:
IEnumerable<T> FindAll<TRelated>(Specification<T> specification,
Expression<Func<T, TRelated>> fetchExpression);
I need to pass in more than one expression. I was thinking about changing the signature to:
IEnumerable<T> FindAll<TRelated>(Specification<T> specification,
IEnumerable<Expression<Func<T, TRelated>>> fetchExpression);
- Is this possible?
- How do I create an array, say, of expressions to pass into this method?
Currently I'm calling the method from my service layer like this:
var products = productRepository.FindAll(spec开发者_运维技巧ification,p => p.Variants);
But I'd like to pass p => p.Variants
and p => p.Reviews
for example. And then in the repository I'd like to iterate through the expression and add them to a query.
For a bit of background on why I am doing this see Ben Foster's blog post on Eager loading with NHibernate.
You could use params to do it:
IEnumerable<T> FindAll(Specification<T> specification,
params Expression<Func<T, object>>[] fetchExpressions)
{
var query = GetQuery(specification);
foreach(var fetchExpression in fetchExpressions)
{
query.Fetch(fetchExpression);
}
return query.ToList();
}
You can call this like so:
var products = productRepository.FindAll(specification,
p => p.Variants, p => p.Reviews );
You can change your call to this:
var products = productRepository.FindAll(specification,
new [] { p => p.Variants,
p => p.Reviews });
But this will only work if the T
is the same in both!
精彩评论