autonomatt
autonomatt

Reputation: 4433

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);
  1. Is this possible?
  2. 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(specification,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.

Upvotes: 3

Views: 2296

Answers (2)

Chris Kooken
Chris Kooken

Reputation: 33948

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 );

Upvotes: 5

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174477

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!

Upvotes: 0

Related Questions