繁体   English   中英

实体框架动态Where子句

[英]Entity Framework Dynamic Where Clause

我有一个查询:

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();
}

这可能吗?

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

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

看这篇文章

LINQ to entities - 构建where子句以在多对多关系中测试集合

编辑 :在您的帖子更新后,这似乎不再相关; 我会留下它,以防它有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM