2012-09-07 28 views
0

我正在使用EF4.3以及工作單元+存儲庫模式。可以在這裏結合linq謂詞嗎?

我有一個方法作爲一些其他方法的基礎,這裏是代碼的外觀。

這是我的「基地」方法:

public static IQueryable<Deal> FindActive() 
    { 
     var r = new ReadRepo<Deal>(Local.Items.Uow.Context); 

     return r.Find(d => 
      d.ActiveFrom <= DateTime.Now && 
      (d.ActiveUntilComputed == null || d.ActiveUntilComputed > DateTime.Now) && 
      d.Published); 
    } 

這裏是調用基方法的方法之一:

public static IQueryable<Deal> FindActiveByStore(int storeId) 
    { 
     Guard.Default(storeId, "storeId"); 
     return FindActive().Where(d => d.StoreId == storeId); 
    } 

正如你可以FindActiveByStore看到的,我首先調用FindActive,然後鏈接Find()。 FindActive後面跟着一個Where()來添加一個輔助謂詞(原因在於術語)。

我想知道是否有可能將謂詞傳遞給FindActive而不是使用Where(),事實上它是否會影響性能。

像這樣:

FindActive(d => d.StoreId == storeId) 

FindActive已傳遞一個謂詞Find()所以它需要兩個結合起來。

我在猜測我回來的答案會在努力或表現方面「不值得」,但我想我會問問專家。

回答

0

您可以使用此代碼(您減少代碼的行數)

public IQueryable<Deal> FindActiveByStore(Expression<Func<Deal,bool>> predicate) 
{ 
    var r = new ReadRepo<Deal>(Local.Items.Uow.Context); 

    return r.Find(d => d.ActiveFrom <= DateTime.Now 
      && (d.ActiveUntilComputed == null || d.ActiveUntilComputed > DateTime.Now) 
      && d.Published) 

      .Where(predicate); 
} 
+0

奇怪。添加.Where(m => m.AnotherField!= null)工作,但WhereWith(謂詞)不) - 提供語法...不包含'Where'的定義 – dotnetnoob

+0

@ user1437135因爲有混合在一個泛型謂詞(T)'和交易之間。如果你用功能定義中的交易替換T,它將起作用 –

+0

@ user1437135我編輯了答案,應該更好地工作。 –