簡體   English   中英

用於構造 OData 查詢選項的強類型 Linq

[英]Strong-typed Linq to construct OData query options

假設以下示例演示了如何使用HttpClient執行讀取操作:

using (var client = new HttpClient())
{
    client.BaseAddress = webUri;
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

    var requestUrl = "/api/products?$filter=(Category eq 'Cars')";

    var response = await client.GetAsync(requestUrl);
    if (response.IsSuccessStatusCode)
    {
       var products = await response.Content.ReadAsAsync<List<Product>>();
    }
}

到目前為止一切都很好,但是從 Linq 查詢構造 REST 端點 Url 怎么樣?

總而言之,目標是利用強類型 Linq 表達式來構建 REST 端點 Url,例如查詢:

var products = client.Get<List<Product>>().Where(p => p.Category == "Cars");

將轉化為:

/api/products?$filter=(Category eq 'Cars')

是否有任何.Net 庫允許將 Linq 表達式轉換為 OData 查詢選項字符串?

您可以使用 WCF 數據服務客戶端為您構建查詢,然后解析結果。

// url doesn't matter unless you will use data service to execute the call
var dsContext = new DataServiceContext(new Uri("http://stackoverflow"));
// need to pass in the controller into CreateQuery - could create an extension method to pluralize the type to not have to pass it in. 
var query = dsContext.CreateQuery<Product>("/api/products").Where(p => p.Category == "Cars");
// ToString will output the url
var uri = new Uri(query.ToString());
// Grab just the path and query
var path = new Uri(uri.PathAndQuery, UriKind.RelativeOrAbsolute);
await client.GetAsync(path); // this will call the api not DataServiceContext

但是,如果您要使用 DataServiceContext,那么您可能只想使用它來為您執行查詢,而不是使用 httpclient - 這適用於 OData V1-3 我不知道它是否適用於 V4。 查詢變量將是一個 IQueryable,您可以直接執行它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM