Question

I have a Repository pattern for product entity and I have a method that retrieves a product by id. Each product has a category, among other complex properties. In some cases I want to retrieve the products without the category (lazy loading) but in some cases I want to return both entities (products and categories). Is there any better option that having two methods? this is what I coded:

Product GetById(int id) 
{ 
     // without includes
     ... 
}

Product GetByIdFull(int id) 
{ 
     // with includes
     ...
}
Was it helpful?

Solution

You can do something like this:

public Product Get(int id, params Expression<Func<TEntity, object>>[] propertiesToInclude)
{
    var query = context.Products;
    foreach (var expression in propertiesToInclude)
    {
        query = query.Include(expression);
    }
    return query.SingleOrDefault(p => p.id == id);
}

The calling code could optionally specify the properties to be included using a lambda like so:

var justProduct = repo.Get(productId);
var productAndCategory = repo.Get(productId, p => p.Category);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top