【问题标题】:Strong-typed Linq to construct OData query options用于构造 OData 查询选项的强类型 Linq
【发布时间】:2014-09-14 20:04:33
【问题描述】:

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

【问题讨论】:

    标签: c# linq odata


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-07
      • 2011-09-05
      • 2013-08-23
      • 1970-01-01
      • 2012-08-23
      • 1970-01-01
      相关资源
      最近更新 更多