Search code examples
c#entity-frameworklambdaexpression-trees

Expression conversion


I am still a little green to Expressions and having difficulty figuring this problem out. This may be more of a Lambda expression issue over EF, but I am hoping someone can atleast point me in the correct direction:

I am attempting to do the following:

internal static IQueryable<TSource> WithSecurity<TSource>(thisIQueryable<TSource> source, Expression<Func<Security.Access, TSource, bool>> predicate, params MyRoles[] roles)
{

    DL.MyContext ctx = Csla.Data.DbContextManager<DL.MyContext>.GetManager().DbContext;

    var accessData = ctx.Access.Where(e => roles.Contains((MyRoles)e.Role_ID));

    Expression x = predicate asLambdaExpression;

    source =
        from c in source
        where accessData.Any(predicate)
        select c;

    return source;
}

On the where clause, there is clearly a problem as the predicate is of type Expression<Func<Security.Access, TSource, bool>>, but the Any is expecting Expression<Func<Security.Access, bool>>. Any assistance on how to convert will be greatly appreciated.


Solution

  • I think what you are looking for is the Compile method:

    var compiledPredicate = predicate.Compile();
    source = 
        from c in source 
        where accessData.Any(ad => compiledPredicate(ad, c)) 
        select c; 
    

    Note that Compile is a somewhat expensive operation so if this methods gets invoked frequently with the same expression in a typical scenario consider caching the result from Compile().