[英]Combining LINQ with OData AddQueryOption
OData的限制( 此處列出 )阻止我從我的OData源添加動態where子句到數據集。 我發現之前的帖子回答了我對動態過濾器的查詢,即將AddQueryOption方法與自定義構建的查詢字符串一起使用。 但是,似乎沒有辦法將此查詢字符串與標准LINQ查詢組合在一起。
使用上述方法生成有效查詢:
https://api-dev.company.com/odata/Assets?$filter=(Levels/any(l:l/LevelId eq 18)) or (Levels/any(l:l/LevelId eq 19))
這必須動態生成的原因是因為有一些可變數量的級別過濾器在運行時無法確定,只需使用多個Where子句生成“和”過濾器而不是“或”過濾器,如下所示:
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);
我想知道是否有一種方法可以手動編輯字符串,或者是否有合適的方法來組合兩種查詢字符串生成方法。 謝謝你的時間。
經過一些反復試驗后,我發現利用這里解答的解決方案有助於解決這個問題。 我的解決方案是在LINQ 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”選項,否則會拋出異常。
如果在調用GetDynamicQuery(assets);
之前where子句中已存在DateTime過濾器,則會出現錯誤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.
調用odata web api時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.
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.
我已經通過這個鏈接發布了這個問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.