2015-07-20 139 views
1

OData的限制(listed here)阻止我將動態where子句添加到來自OData源的數據集。我發現了一個previous post,它回答了我對動態過濾器的查詢,即將AddQueryOption方法與定製的查詢字符串一起使用。但是,似乎沒有辦法將此查詢字符串與標準LINQ查詢結合起來。將LINQ與OData結合使用AddQueryOption

使用上述方法產生一個有效的查詢:

https://api-dev.company.com/odata/Assets?$filter=(Levels/any(l:l/LevelId eq 18)) or (Levels/any(l:l/LevelId eq 19)) 

這具有被監守有不能運行時間之前來確定級別過濾器的可變數目和簡單地使用多個何處被動態地產生的原因條款生產「和」過濾器,而不是「或」過濾器,這樣的:

https://api-dev.company.com/odata/Assets?$filter=(Levels/any(l:l/LevelId eq 18)) and (Levels/any(l:l/LevelId eq 19)) 

我當前嘗試此方法後使用LINQ產生的輸出:

https://api-dev.company.com/odata/Assets?$filter=DisplayOnline and Status eq Tools.Services.Models.EPublishStatus'Active', and (Levels/any(l:l/LevelId eq 18)) or (Levels/any(l:l/LevelId eq 19)) 

請注意,第二個查詢只有它的錯誤是Levels過濾器和其他過濾器之間的逗號。

額外的Where子句如下:

// Filter by assets that can be displayed online 
assets = assets.Where(a => a.DisplayOnline); 

// Filter by assets that are active 
assets = assets.Where(a => a.Status == EPublishStatus.Active); 

我想知道是否有手動編輯字符串的方式或者如果有兩個查詢字符串生成方法相結合之有道。謝謝你的時間。

回答

1

經過一些試驗和錯誤,我發現利用解決方案answered here幫助解決了這個問題。對我來說,解決方案是構建動態過濾查詢LINQ AFTER Where子句,然後使用兩個綜合作用的結果建立一個全新的查詢:這裏

// Filter by assets that can be displayed online 
assets = assets.Where(a => a.DisplayOnline); 

// Filter by assets that are active 
assets = assets.Where(a => a.Status == EPublishStatus.Active); 

// Addtional filters.. 
assets = assets.Where(a => x == y); 

// Get the string for the dynamic filter 
string dynamicQuery = GetDynamicQuery(assets); 

// Get base OData Asset call (https://api-dev.company.com/odata/Assets) 
IQueryable<Asset> serviceCall = _container.Assets; 

// Apply the new dynamic filter 
serviceCall = serviceCall.AddQueryOption("$filter", dynamicQuery); 

// Resultant OData query (Success!) 
https://api-dev.company.com/odata/Assets?$filter=DisplayOnline and Status eq Models.Status'Active' and (Levels/any(l:l/LevelId eq 18)) or (Levels/any(l:l/LevelId eq 19)) 

訣竅是確保只有一個查詢中的「$ filter」選項,否則會引發異常。

0

它會給你一個錯誤,如果有一個DateTime過濾器where子句中已經存在調用GetDynamicQuery(assets); 錯誤會是這樣使用新的URL請求message=The time zone information is missing on the DateTimeOffset value '2016-09-20T23:54:23.4531408'. A DateTimeOffset value must contain the time zone information. 我已經張貼quation在打電話給OData的網絡API時,像以前一樣這link