[英]Entity Framework Dynamic Where Clause
I have a query like: 我有一个查询:
var function = GetSomeExpression();
using (FooModel context = new FooModel())
{
var bar = context.Bar.Where(function);
}
I'd like to make a generic method that can execute Where against different Entities in the context. 我想创建一个可以在上下文中针对不同实体执行Where的泛型方法。 The goal is not having to do context.Bar.Where, context.Car.Where, Context.Far.Where, etc.
目标不是必须做context.Bar.Where,context.Car.Where,Context.Far.Where等。
Something that cannot be done, but illustrates the goal is: 一些无法做到的事情,但说明了目标是:
var q = context.GetObjectContext(T).Where(queryFunction);
I have looked into using Relfection and can get the Where method, but do not know how to execute it against the context passing in the delegate. 我已经研究过使用Relfection并且可以获取Where方法,但是不知道如何针对在委托中传递的上下文执行它。 I also looked at DynamicMethod, but doing the whole IL thing does not like appealing.
我也看过DynamicMethod,但做整个IL事情并不喜欢吸引人。
What I have so far: 到目前为止我所拥有的:
private List<T> GetResults<T>(Expression<Func<T, bool>> 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<T> result = whereMethod.Invoke(
// have the method info
// have the expression
// can reference the context
);
throw new NotImplementedException();
}
Is this possible to do? 这可能吗?
This is way easier then what I was trying before: 这比我之前尝试的方式更容易:
private List<T> GetResults<T>(IQueryable<T> source,
Expression<Func<T, bool>> queryFunction)
{
return source.Where(queryFunction).ToList<T>();
}
see this post 看这篇文章
LINQ to entities - Building where clauses to test collections within a many to many relationship LINQ to entities - 构建where子句以在多对多关系中测试集合
Edit : after your post update this doesn't seem relevant anymore; 编辑 :在您的帖子更新后,这似乎不再相关; I'll leave it in case it's helpful.
我会留下它,以防它有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.