entity framework动态Where子句

我有一个查询:

var function = GetSomeExpression(); using (FooModel context = new FooModel()) { var bar = context.Bar.Where(function); } 

我想创建一个generics方法,可以在上下文中针对不同的实体执行Where。 目标不是必须做context.Bar.Where,context.Car.Where,Context.Far.Where等。

一些无法完成的事情,但说明了目标是:

 var q = context.GetObjectContext(T).Where(queryFunction); 

我已经研究过使用Relfection并且可以获取Where方法,但是不知道如何针对在委托中传递的上下文执行它。 我也看过DynamicMethod,但做整个IL事情并不喜欢吸引人。

到目前为止我所拥有的:

 private List GetResults(Expression<Func> queryFunction) { // note: first() is for prototype, should compare param type MethodInfo whereMethod = typeof(Queryable).GetMethods() .Where(m => m.Name == "Where") .First().MakeGenericMethod(typeof(T)); // invoke the method and return the results List result = whereMethod.Invoke( // have the method info // have the expression // can reference the context ); throw new NotImplementedException(); } 

这可能吗?

这比我之前尝试的方式更简单:

 private List GetResults(IQueryable source, Expression> queryFunction) { return source.Where(queryFunction).ToList(); } 

看这篇文章

LINQ to entities – 构建where子句以在多对多关系中测试集合

编辑 :在您的post更新后,这似乎不再相关; 我会留下它,以防它有用。