Creating a Linq expression dynamically containing a subquery

后端 未结 2 499
一个人的身影
一个人的身影 2021-01-05 18:16

I recently stumpled upon the problem to dynamically create Linq expressions during runtime. Most examples I found deal with the rather simple task of just comparing one prop

相关标签:
2条回答
  • 2021-01-05 18:56

    I recommend you look at these links:

    Joseph and Ben Albahari's PredicateBuilder

    The LINQ dynamic query library

    I haven't used either for a while, but one or the other should help.

    0 讨论(0)
  • 2021-01-05 19:07

    Found a solution that is working in my particular use case and does exactly what I was looking for.

    /* 
    building expression tree 
    example: Session.Query.Where(m => m.SpecialProperty.Any(f => f.Name.Contains("test")))
    */ 
    
    var innerItem = Expression.Parameter(typeof(MyInnerClass), "f");
    var innerProperty = Expression.Property(innerItem, "Name");
    var innerMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) });
    var innerSearchExpression = Expression.Constant(searchString, typeof(string));
    var innerMethodExpression = Expression.Call(innerProperty, innerMethod, new[] { innerSearchExpression });
    var innerLambda = Expression.Lambda<Func<MyInnerClass, bool>>(innerMethodExpression, innerItem);
    
    var outerItem = Expression.Parameter(typeof(MyOuterClass), "m");
    var outerProperty = Expression.Property(outerItem, info.Name);
    /* calling a method extension defined in Enumerable */
    var outerMethodExpression = Expression.Call(typeof(Enumerable), "Any", new[] { typeof(MyInnerClass) }, outerProperty, innerLambda);
    var outerLambda = Expression.Lambda<Func<MyOuterClass, bool>>(outerMethodExpression, outerItem);
    query = query.Where(outerLambda);
    

    This rather dowdy approach is needed instead of the more elegant single line LINQ-Expression to allow for parametrization of types and method names. However, I of course wouldn't mind other suggestions and ideas on possible performance penalties.

    It is very likely that this code snippet could also assist in solving How to produce a Subquery using non-generic Lambda.

    0 讨论(0)
提交回复
热议问题