强类型Linq构造OData查询选项

时间:2014-09-14 20:04:33

标签: c# linq odata

假设以下示例演示了如何使用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查询选项字符串?

1 个答案:

答案 0 :(得分:2)

您可以使用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,你可以执行它。