Search code examples
linqlinq-to-nhibernatelinq-expressionsspecification-pattern

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.


Solution

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