vendredi 29 juin 2018

ToList() doesn't apply dynamically generated where clauses Asp.Net Core

ToList() doesn't apply dynamically generated where clauses Asp.Net Core I am building pipeline for filtering. so i have method where i retrieve iqueryable from dbcontext, it looks like the following:

 public IEnumerable<Event> Filter(EventFilterModel filterModel)
    {
        _filterManager = new EventsSelectionPipeline();
        _filterManager.Register(new EventTypeFilter(filterModel.EventTypes, _unitOfWork));

        var events = _unitOfWork.DbContext.Events;
        var filteredEvents = _filterManager.Process(events);

        return filteredEvents.ToList();
    }

Process method:

public override IQueryable<Event> Process(IQueryable<Event> input)
    {
        foreach(var filter in _filters)
        {
            filter.Execute(input);
        }

        return input;
    }

EventTypeFilter :

public class EventTypeFilter : IFilter<IQueryable<Event>>
{
    private readonly IEnumerable<EnumEventType> _eventTypes;
    private readonly IUnitOfWork<ApplicationContext> _unitOfWork;

    public EventTypeFilter(IEnumerable<EnumEventType> eventTypes, IUnitOfWork<ApplicationContext> uow)
    {
        _eventTypes = eventTypes;
        _unitOfWork = uow;
    }

    public IQueryable<Event> Execute(IQueryable<Event> input)
    {
        if (_eventTypes.Any())
        {
            BinaryExpression condition = null;
            var expr = new List<Expression<Func<Event, bool>>>();
            var parameter = Expression.Parameter(typeof(Event), "ev");

            foreach(var eventType in _eventTypes)
            {
                var property = Expression.Property(parameter, "EventType");
                var propType = ((PropertyInfo)property.Member).PropertyType;
                var converter = TypeDescriptor.GetConverter(propType);

                var propertyValue = eventType;
                var constant = Expression.Constant(propertyValue);
                var valueExpression = Expression.Convert(constant, propType);
                var dynExpr = Expression.Equal(property, valueExpression);

                condition = condition == null ? dynExpr : Expression.Or(condition, dynExpr);
            }

            if(condition != null)
            {
                var predicate = Expression.Lambda<Func<Event, bool>>(condition, parameter);

                input = input.Where(predicate);
            }
        }

        return input;
    }
}

In IQueryable<Event> Process(IQueryable<Event> input) method Execute return iqueryable with correct number of elements (with applying filtering), but when i apply toList to iqueryable it just returns me initial set of data without filtering.

Aucun commentaire:

Enregistrer un commentaire