2016-12-29 42 views
2

我嘗試做以下(SelectedIdCollection是列表和cb.Id爲int) -EF6的LINQ - 如何創建一個過濾器表達式等同於 「在哪裏(名單== NULL || List.Contains(OBJ))」?

db.Items.Where(cb => (SelectedIdCollection == null || SelectedIdCollection.Contains(cb.Id))) 

基本上,如果SelectedIdCollection爲null,則返回的一切,如果它不爲空,然後通過它進行過濾。

但它引發以下錯誤 -

「System.NotSupportedException」類型的異常出現在EntityFramework.SqlServer.dll但在用戶代碼中沒有處理。不能 比較元素類型 'System.Collections.Generic.IList`1 [[System.Int32,mscorlib, Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]'。 只有基本類型,枚舉類型和實體類型是支持 。

有沒有其他的方式來寫這個條件?

+1

如何使用'if'(有條件的'Where') –

+1

是否'SelectedIdCollection?。載有(cb.Id)?真正的工作? –

+1

@PatrickHofman那不會編譯。沒有空傳播算子的表達式。 。 – Servy

回答

2

的異常被拋出,因爲你是一個比較運行時變量(SelectedIdCollection != null)和EF不知道如何翻譯成SQL。

你能不能做這樣的事情呢?

var items = db.Items.AsQueryable(); 

if(SelectedIdCollection != null) 
{ 
    items = items.Where(cb => SelectedIdCollection.Contains(cb.Id)); 
} 

if(date1 != null) 
{ 
    items = items.Where(cb => cb.Date1 == date1); 
} 

這將有可能是在SQL也更快,因爲查詢規劃可能會選擇不同的指標,如果它並不需要閱讀所有的列進行過濾。

+1

是的,我可以但最終會在該過濾器中有更多的字段 - .Where(cb =>(amount <0 || cb.amount == amount)&&(date1 == null?cb.Date1 == date1 ))等等等等 – Achilles

+0

你可以鏈接儘可能多的'.Where',所以這應該不成問題? –

+0

Like - if(SelectedIdCollection!= null){ items = items.Where(cb => SelectedIdCollection.Contains(cb.Id)); } if(amount <0){items.Where(cb => cb.Amount = amount);}等等在單獨的if子句中? – Achilles

4

由於SelectedIdCollection是從你的表情外捕捉到的變量,你可以處理它使表達式之前是null,然後把它當作非空:

var getEverything = SelectedIdCollection==null; 
var targetCollection = SelectedIdCollection ?? new int[0]; 
var res = db.Items.Where(cb => getEverything || targetCollection.Contains(cb.Id)); 

現在targetCollection是保證非 - nullgetEverything標誌涵蓋了需要從數據庫中選擇所有內容的情況。

相關問題