我有这样一个查询:实体框架动态Where子句
var function = GetSomeExpression();
using (FooModel context = new FooModel())
{
var bar = context.Bar.Where(function);
}
我想提出可以执行对哪里的背景下,不同实体的通用方法。我们的目标是不是有做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]”); –
bendewey
2009-02-10 19:17:53