Search code examples
c#neo4jclient

Can I call Cypher's .Return with a Func<>?


I'm working with the Neo4jClient for C# and it works brilliantly ! Thanks Tatham Oddie.

At runtime, I need to return different results based on some criteria though. I see Return is defined and overloaded as basically:

ICypherFluentQuery<TResult> Return<TResult>(Expression<Func<ICypherResultItem, TResult>> expression);

Since TResult is a templated param, I'm not sure how I could create a Func<> that I can pass to .Return

Ideally, I'd like to do something like this:

Func<ICypherResultItem, User> returnCode = (user) => new { u = user.As<User> } ;

var query = client
    .Cypher
    .Start(new { root = client.RootNode })
    .Match("root-[:HAS_BOOK]->user");
    .Return(   returnCode );

Is this possible ? How can I declare the Func<> to pass to Return ?


Solution

  • Declare your returnCode variable as Expression<>> and compiler will generate expression for you:

    When a lambda expression is assigned to a variable, field, or parameter whose type is Expression<TDelegate>, the compiler emits instructions to build an expression tree.

    from Expression Class

    But because your lambda returns anonymous type, instead of User class instance, your Func<T, TRresult> generic parameter does not match. Try with following:

    Expression<Func<ICypherResultItem, User>> returnCode = (user) => user.As<User>;