How can we apply conditional include using includeProperties in generaic repository pattern?

asp.net-mvc c# entity-framework-6 repository-pattern

Question

We are using Entity framework along with the generic repository pattern.

When loading multiple entities we use includeProperties string filter in generic repository pattern.

Following is the code I have in my service class,

customerRepository.Get (filter: c => ! c.IsDeleted, includeProperties : "Orders");

Following is the code I have in my Generic Repository

 public virtual IEnumerable<TEntity> Get(
            Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            string includeProperties = "",
            Func<TEntity, TEntity> selectColumns = null)
{
    IQueryable<TEntity> query = dbSet;

    if (filter != null)
    {
        query = query.Where(filter);
    }

    if (selectColumns != null)
    {
        query = query.Select(selectColumns).AsQueryable();
    }

    query = includeProperties.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Aggregate(query, (current, includeProperty) => current.Include(includeProperty));

    return orderBy != null ? orderBy(query).ToList() : query.ToList();
}

It is possible that a customer can have multiple orders which are already deleted. However using above includeProperties we are only able to load all orders of a customer.

How can we load only non deleted orders of a customer?

i.e. How can we apply conditional include using includeProperties in generaic repository pattern?

We tried the code below but it did not work:

customerRepository.Get (filter: c => ! c.IsDeleted && ! c.Orders.IsDeleted, includeProperties : "Orders");
1
2
3/28/2016 10:25:21 AM

Accepted Answer

Note that it is not currently possible to filter which related entities are loaded. Include will always bring in all related entities. Msdn Reference

In this repository pattern you cannot do this with this specified method.

You can extend your repository to return IQuerable and do the same.

public virtual IQueryable<TEntity> GetAsQueryable(Expression<Func<TEntity, bool>> where)
{
    return _dataContext.TEntity.Where(where).AsQueryable();
}

See reference

Request this feature here

In order to filter child collection you need something similar to this.

var anonymousProjection = dbContext.CustomerEntity
                                 .Where(c => ! c.IsDeleted)
                                 .Select(x=> new 
                                  {
                                       customers = x,
                                       orders = x.Orders.Where(h=>h.IsDeleted)
                                  }).ToList();

Similar answer

1
5/23/2017 12:15:32 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow