簡體   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