如何仅通过Expression创建where子句

时间:2015-04-14 05:12:19

标签: c# linq entity-framework expression-trees

我想要实现的是带有表达式树的简单where子句(仅限):

Tags.Where(t => t.Title == "Exam")

到目前为止我做了什么:

ParameterExpression pe = Expression.Parameter(typeof(EfTag), "t");
Expression left = Expression.Property(pe, typeof(EfTag).GetProperty("Title"));
Expression right = Expression.Constant("Exam");
Expression e1 = Expression.Equal(left, right);

var neededTags = myDataContext.Tags.where( e1 /* what should i do here WI?? */ );

请不要将我推荐给System.Linq.DynamicLinqKit。我需要在不使用任何第三方库的情况下执行此操作。

1 个答案:

答案 0 :(得分:2)

你几乎就在那里。现在您已经有参数和==运算符调用,您必须将它们组合成Lambda

var predicate = Expression.Lambda<Func<EfTag, bool>>(e1, pe);

您稍后可以在Where来电:

中使用它
var neededTags = myDataContext.Tags.Where(predicate);