Create fully dynamic where clause with expression tree and execute on IQueryable

我与影子孤独终老i 提交于 2019-12-04 04:26:01

This is quite hard to look at in isolation, but the first thing that occurs is that Compile looks out of place for IQueryable - that will rarely work (LINQ-to-Objects being the exception).

An equivalent to WhereClause.Invoke(C.ClientID) is to use Expression.Invoke to call a sub-expression, but even this is flakey: LINQ-to-SQL will support it, EF (in 3.5 at least) doesn't (maybe "didn't"; I haven't re-checked in 4.0). Ultimately, it would be more robust to create lambda1 as an Expression<Func<Employee,bool>> if possible:

    ParameterExpression empParam = Expression.Parameter(typeof(Employee),"emp");
    ConstantExpression equalTarget = Expression.Constant(idToDelete, idToDelete.GetType());
    BinaryExpression intEqualsID = Expression.Equal(
        Expression.PropertyOrField(empParam, targetProperty), equalTarget);
    Expression<Func<Exmployee, bool>> lambda1 =
                Expression.Lambda<Func<int, bool>>(
                intEqualsID,
                empParam);

Then pass this to Where:

var query1 = employees.Where(lambda1);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!