【问题标题】:Entity Framework Dynamic Where Clause实体框架动态 Where 子句
【发布时间】: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


【解决方案1】:

这比我之前尝试的要容易得多:

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

【讨论】:

    【解决方案2】:

    看这篇文章

    LINQ to entities - Building where clauses to test collections within a many to many relationship

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

    【讨论】:

    • 没有帮助。这让我意识到我做得比我需要的要多,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2011-12-31
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多