实体框架动态Where子句

blu*_*blu 6 c# generics entity-framework

我有一个查询:

var function = GetSomeExpression();    

using (FooModel context = new FooModel())
{
    var bar = context.Bar.Where(function);
}
Run Code Online (Sandbox Code Playgroud)

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

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

var q = context.GetObjectContext(T).Where(queryFunction);
Run Code Online (Sandbox Code Playgroud)

我已经研究过使用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();
}
Run Code Online (Sandbox Code Playgroud)

这可能吗?

blu*_*blu 7

这比我之前尝试的方式更容易:

private List<T> GetResults<T>(IQueryable<T> source, 
    Expression<Func<T, bool>> queryFunction)
{
   return source.Where(queryFunction).ToList<T>();
}
Run Code Online (Sandbox Code Playgroud)