2010-05-10 125 views
2

我有Linq to Entity查詢,就像你可以看到下面我在我的代碼中使用它五次,所有改變的是where子句。是否有可能創建一個方法並傳遞值,而不是將所有代碼寫入五次。謝謝Linq to Entity動態where子句

items = from t1 in _entities.table1 
         join t2 in _entities.Table2 on t1.column1 equals t2.column1 
         join t3 in _entities.Table3 on t1.column2 equals t3.column2 
         join t4 in _entities.Table4 on t1.column3 equals t4.column3 

         where **t1.column5 == Something** 
         select new 
           { 
            t1.column7, 
            t2.column8,           
            t3.column9, 
            t4.column10 

           }; 
+1

你沒有導航性能? – LukLed 2010-05-10 19:30:24

回答

3

寫基函數

public IQueryable<Object> Select() 
{ 
    return (from t1 in _entities.table1 
         join t2 in _entities.Table2 on t1.column1 equals t2.column1 
         join t3 in _entities.Table3 on t1.column2 equals t3.column2 
         join t4 in _entities.Table4 on t1.column3 equals t4.column3 
         select new 
           { 
            t1.column7, 
            t2.column8,           
            t3.column9, 
            t4.column10, 
            t1.column5 
           }).AsQueryable<Object>(); 
} 

然後起作用的一種

public IQueryable<Object> SelectWhere1(object condition) 
{ 
    return Select().Where(i=>i.column5==condition); 
} 

public IQueryable<Object> SelectWhere2(object otherCondition) 
{ 
    return Select().Where(i=>i.column7==otherCondition); 
} 

....

+0

不錯的解決方案,一次調整:不要返回IEnumerable,而是返回IQueryable。否則,它將回退到使用Linq-to-objects並在內存中執行過濾。 – 2010-05-10 18:08:17

+0

@Anders Abel:感謝您的提示 – Gregoire 2010-05-10 18:17:39

+0

好吧,當我嘗試使用這種方式我得到的錯誤。實例參數不能從'System.Linq.IQueryable'轉換爲System.Collections.Generic.IEnumberable 。 – GodSmart 2010-05-10 19:08:57

1

如果你寫它的函數形式,你可以做它:

DoQuery(Expression<Func<Table1Type, bool> lambda) 
{ 

    return _entities.table1 
      // Skipping the joins... 
      .Where(lambda) 
      .Select(t => new { t1.column7 }); 
} 

然後,您可以將其稱爲:

DoQuery(t => t.column5 == Something); 
+0

在這個例子中,它也不是所有的基礎。 – GodSmart 2010-05-10 19:11:47

+0

對不起,我沒有開發者。這臺計算機上的環境 - 我會嘗試明天更新它,當我可以測試它。 – 2010-05-10 19:33:13