【发布时间】:2010-10-06 17:29:00
【问题描述】:
我有一个类似的查询:
var function = GetSomeExpression();
using (FooModel context = new FooModel())
{
var bar = context.Bar.Where(function);
}
我想创建一个通用方法,可以针对上下文中的不同实体执行 Where。目标是不必做 context.Bar.Where、context.Car.Where、Context.Far.Where 等。
不能做但说明目标的事情是:
var q = context.GetObjectContext(T).Where(queryFunction);
我已经研究过使用 Relfection 并且可以获得 Where 方法,但不知道如何针对在委托中传递的上下文执行它。我也看了 DynamicMethod,但做整个 IL 的事情并不吸引人。
到目前为止我所拥有的:
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();
}
这可能吗?
【问题讨论】:
-
我曾尝试这样做一段时间,并最终为每个人构建了一个存储库。我想知道其他人的想法。 Designer.cs 生成一个 ctx.CreateQuery
("[Bar]");
标签: c# entity-framework generics