jeudi 11 avril 2019

Getting in a mess with generic IQueryable

I have this code. It takes a generic IQueryable and applies an additional where clause if the object type is Event.

public static IQueryable<T> ApplyFrontEndWhereClause<T>(IQueryable<T> data) where T: BaseEntity<T>
        {
            switch(typeof(T).Name)
            {
                case nameof(Event):
                    return (IQueryable<T>)((IQueryable<Event>)data).Where(Event.FrontEndFilter());
                default:
                    return data;
            }
        }

It works, but it is messy. I am specifically looking to reduce the amount of casting in this line:

return (IQueryable<T>)((IQueryable<Event>)data).Where(Event.FrontEndFilter());

The Event.FrontEndFilter method is as follows:

public static Expression<Func<Event, bool>> FrontEndFilter()
        {
            return (x => x.Date.Day >= DateTime.UtcNow.Day); // Only show future events
        }

How can I make this pattern less confusing for other developers that have to extend this in future? Happy to re-work / re-architect the whole thing if needed!

Aucun commentaire:

Enregistrer un commentaire