Building Expression Tree for string.Contains [duplicate]

寵の児 提交于 2019-12-03 15:23:55

You are almost there, but your parameter expression should be of type T, not String, you are also missing the expression that is getting the property from type T like name.

What you should roughly have is this

val -> Expression.Constant(typeof(string), rule.Field)
parameter -> Expression.Parameter(typeof(T), "p")
property -> Expression.Property(parameter, "PropertyName")
contains -> Expression.Call(property, containsmethod, val)
equals true -> Expression.True or equals, something like that

I am freehanding all of that, so it's likely somewhat different to be valid. The resulting expression should be something like this

p => p.Name.Contains(val)

If you want to create Where query, you must create lambda then call Where on query and pass lambda. Try this:

Expression<Func<T, bool>> lambda = Expression.Lambda<Func<T, bool>>(call, parameter);
MethodCallExpression expression = Expression.Call(typeof(Queryable), "Where",
                                    new[] { typeof(T) }, query.Expression, lambda);
query = query.Provider.CreateQuery<T>(expression);

instead of

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