用于构造 OData 查询选项的强类型 Linq [英] Strong-typed Linq to construct OData query options

查看:69
本文介绍了用于构造 OData 查询选项的强类型 Linq的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设以下示例演示如何使用 HttpClient:

Assume the following example that demonstrates how to perform read operation using 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?

So far so good, but what about constructing REST endpoint Url from a Linq query?

总而言之,目标是利用强类型的 Linq 表达式来构建 REST 端点 Url,例如查询:

To summarize, the goal is to utilize strong-typed Linq expression for constructing REST endpoint Url, for example the query:

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

将转化为:

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

是否有任何允许将 Linq 表达式转换为 OData 查询选项字符串的 .Net 库?

Are there any .Net library that allows to transform Linq expression into OData query option string?

推荐答案

您可以使用 WCF 数据服务客户端为您构建查询,然后解析出结果.

You can use the WCF Data Service client to build the query for you then parse out the result.

// 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,您可以直接执行它.

But if you are going to use DataServiceContext then you might just want to use it to execute the query for you instead of using httpclient - this works for OData V1-3 I don't know if it works for V4. The query variable will be an IQueryable and you could just execute it.

这篇关于用于构造 OData 查询选项的强类型 Linq的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆