0

I have this linq query (using linq 4.3.0):

return ExecuteODataQuery(Db.AdvisorFees, f => f.Advisor);

Implemented as follows:

protected IQueryable<TType> ExecuteODataQuery<TType>(IQueryable<TType> queryFunc, Func<TType, Advisor> advisorFunc) where TType : Entity
    {
        var systemAccount = GetSystemAccountThrow();

        var results = queryFunc.Where(x => x.Active).AsEnumerable().Where(x => CheckAdvisorOrChannel(systemAccount, advisorFunc(x)));

        return results;
    }

This is my custom method:

        public static bool CheckAdvisorOrChannel(SystemAccount systemAccount, Advisor advisor)
    {
        return (systemAccount.IsChannelSystemAccount ? systemAccount.Channel.Code == advisor.Channel.Code : systemAccount.Advisor.Code == advisor.Code);
    }

This currently works. If I remove the AsEnumerable() I get a LinqToEntities not supported exception on my custom method. I cannot use AsEnumerable() as I have too many records and do not want to do the rest of the filtering in memory. Is it possible to call a custom method on IQueryable instead? I've been playin with extension methods and expressions but have not managed to get this working yet. Any pointers?

I would prefer to not use expression trees as much as possible.

newbie_86
  • 4,520
  • 17
  • 58
  • 89
  • Possible duplicate of [Building a dynamic expression tree to filter on a collection property](https://stackoverflow.com/questions/8977895/building-a-dynamic-expression-tree-to-filter-on-a-collection-property) – barakcaf Nov 20 '17 at 09:48
  • @barakcaf Thanks, I did see that, I was hoping there was a solution without using expression trees. – newbie_86 Nov 20 '17 at 10:01
  • You can't get away from expressions but you don't necessarily have to manually construct a tree. Where on IQueryable takes an Expression so you can just call a custom method that returns an Expression of the right type and just define it in the method. – Mant101 Nov 20 '17 at 14:29
  • @Mant101 I've been trying with expressions. The problem is the advisorFunc(x). I get a Not Supported exception. Linq to Entities can't convert it into a store expression. How would I handle that? – newbie_86 Nov 20 '17 at 19:18
  • If you want to be flexible you are going to need to make the advisorFunc an expression. Then take the body and use that in a second expression that creates the conditional operator. How many values does it need to have and are they likely to change? Can you get away with a switch statement and a set of hard coded expressions? Thats ugly but if you want to avoid expression trees it will work. – Mant101 Nov 21 '17 at 16:15

0 Answers0