C# 实体框架动态 Where 子句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/533673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Entity Framework Dynamic Where Clause
提问by blu
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. The goal is not having to do context.Bar.Where, context.Car.Where, Context.Far.Where, etc.
我想制作一个通用方法,可以在上下文中针对不同的实体执行 Where。目标不是必须做 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. I also looked at DynamicMethod, but doing the whole IL thing does not like appealing.
我已经研究过使用 Relfection 并且可以获得 Where 方法,但不知道如何针对传递给委托的上下文执行它。我也看过 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?
这是可能的吗?
采纳答案by blu
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>();
}
回答by Michael G
see this post
看到这个帖子
LINQ to entities - Building where clauses to test collections within a many to many relationship
LINQ to entity - 构建 where 子句以测试多对多关系中的集合
Edit: after your post update this doesn't seem relevant anymore; I'll leave it in case it's helpful.
编辑:在您的帖子更新后,这似乎不再相关;如果有帮助,我会留下它。