2016-03-05 28 views
1

我想通過變量y聲明並重用Expression。在一個方法我有類似以下內容:將參數傳遞給實體框架中的可重用表達式

Expression<Func<Item, int, bool>> exFilter = (x, y) => x.Item.Id == y; 

而且上,在代碼我試圖使用聲明表達(exFilter)

return context.Item.Select(x => new { data = exFilter.Where(exFilter)) 

問:我如何通過參數的exFilter ?我想要做的選擇按列表(x)中的每個項目進行過濾。

這只是我試圖弄清楚的一個例子。問題和查詢更大更復雜。

+0

是'context.Item'的DbSet? –

+1

'exFilter.Where(exFilter)'是什麼意思? –

+0

是的,它是一個DbSet。這只是一個過濾器,exFilter就是表達式裏面的地方。 – user2457382

回答

1

您可以使用LinqKit重用,你有表達。這裏是一個例子:

var result = 
    context.Item //The DbSet 
    .AsExpandable() //This method is defined in LinqKit and allows for expression expansion 
    .Where(x => exFilter.Invoke(x, 2)) //LinqKit will know how to translate this into an expression 
    .ToList(); 

我在這裏使用值2作爲例子。

0

你可以嘗試這樣的事情:

public class Item 
{ 
    public Item(String str, Int32 @int) 
    { 
     this.StrValue = str; 
     this.IntValue = @int; 
    } 
    public String StrValue { get; } 
    public Int32 IntValue { get; } 
    public override string ToString() => 
     $"{this.IntValue} = '{this.StrValue}'"; 
} 


public static class ExpressionExtensions 
{ 
    public static Expression<Func<TItem, TResult>> Curry<TItem, TCurry, TResult>(
     this Expression<Func<TItem, TCurry, TResult>> function, 
     TCurry value) 
    { 
     if (function == null) 
      throw new ArgumentNullException(paramName: nameof(function)); 

     var itemParameter = Expression.Parameter(typeof(TItem)); 
     var valueConstant = Expression.Constant(value); 

     return Expression.Lambda<Func<TItem, TResult>>(
      Expression.Invoke(
       function, 
       new Expression[] 
       { 
        itemParameter, 
        valueConstant 
       }), 
      new[] { itemParameter }); 
    } 
} 

...

var items = new[] 
{ 
    new Item("one", 1), 
    new Item("two", 2), 
    new Item("two again", 2), 
}; 

Expression<Func<Item, Int32, Boolean>> predicate = (item, intValue) => 
    item.IntValue == intValue; 

var curriedPredicate = predicate.Curry(2); 

var filtered = items 
    .AsQueryable<Item>() 
    .Where(curriedPredicate) 
    .ToArray(); 

foreach (var item in filtered) 
{ 
    Console.WriteLine(item); 
} 
相關問題