Flash_Back Flash_Back - 1 month ago 11
C# Question

'Invoke' node is not supported in LINQ when nesting Expression Functions

I am trying to nest

Expression Functions
, I've tried multiple things (
Invoke
,
Compile
etc.) and read topics about this exception, but did not see any case appending when nesting expression functions. I don't know much about it, it is pretty new for me, I guess I must have missed something very simple.

My aim is just to be able to nest expressions so that
GetAbilities
could be used in multiple other expressions without having to duplicate its code.

How could I achieve such a thing ?

public static Expression<Func<User, bool>> Test
{
get
{
Expression<Func<User, bool>> res = (u => GetAbilities.Compile()(u).Any());
return res;
}
}

public static Expression<Func<User, IEnumerable<Ability>>> GetAbilities
{
get
{
Expression<Func<User, IEnumerable<Ability>>> res = u => u.AllAbilities.Where(a => a.Type == Ability.TypeE.Initial);
return res;
}
}


In the above example, when retrieving the results of
Test
I got the follwing exception :


The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.

Answer

You can use LinqKit to do something like this:

public static Expression<Func<User, bool>> Test
{
    get
    {
        //Use one expression inside another via Invoke
        Expression<Func<User, bool>> res = (u => GetAbilities.Invoke(u).Any());

        return res.Expand(); //Expand to create a full expression

        //The result would be the same as if you have used
        //u => u.AllAbilities.Where(a => a.Type == Ability.TypeE.Initial).Any()

    }
}
Comments