Question

I just discovered LINQKit and am quite happy that it seems to provide a solution for the common problem of wanting to factor out parts of complex linq queries.

All examples, however, show how to factor out predicates for where-clauses.

Although that's a very typical use-case, I also want to factor out other kinds of expressions, typically for selects. Let's say I have the following sub-expression:

    Expression<Func<SomeFunkyEntity, String>> GetStatusFromSomeFunkyEntity()
    {
        return i =>
            i.IsExercise ? "Excercise" :
            i.IsExpired ? "Expired" :
            (i.IsLocked ) ? "Locked" :
            i.IsAdmitted ? "Admissible" : "Unusable";
    }

Does LINQKit provide a way to expand a call to this? I tried:

var query =
    from i in this.DbContext.MyFunkyEntities.AsExpandable()
    select new SomeFunkyEntityWithStatus()
    {
        FunkyEntity = i,
        Status = GetStatusFromSomeFunkyEntity().Invoke(i)
    };

This complies, but fails at runtime in LINQKit's expander:

Unable to cast object of type 'System.Linq.Expressions.InstanceMethodCallExpressionN' to type 'System.Linq.Expressions.LambdaExpression'.

The stack trace starts with:

at LinqKit.ExpressionExpander.VisitMethodCall(MethodCallExpression m)
at LinqKit.ExpressionVisitor.Visit(Expression exp)
at LinqKit.ExpressionVisitor.VisitMemberAssignment(MemberAssignment assignment)
...

Is this not supported, or do I do something wrong?

Était-ce utile?

La solution

Have you tried to assign the expression to a local variable before calling invoke?

var statusFromSomeFunkyEntity = GetStatusFromSomeFunkyEntity();

var query =
    from i in this.DbContext.MyFunkyEntities.AsExpandable()
    select new SomeFunkyEntityWithStatus()
    {
        FunkyEntity = i,
        Status = statusFromSomeFunkyEntity.Invoke(i)
    };

Check out this answer.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top