简体   繁体   English

如何为Odata创建查询表达式以通过ID获取

[英]How to create query expression for Odata for get by Id

I have created an OData service and now I am trying to consume this service at client side. 我创建了一个OData服务,现在尝试在客户端使用此服务。 I wants to create an expression such as for the below url in the c# query expression- 我想为c#查询表达式中的以下网址创建一个表达式-

http://odata.org/Product-Service/Product(150) http://odata.org/Product-Service/Product(150)

The above url is working fine in browsers but I want to create query expression in the C# for the above url. 上面的URL在浏览器中工作正常,但是我想在C#中为上面的URL创建查询表达式。 Any help would be greatly appreciable. 任何帮助将是非常可观的。

You could use a DataServiceContext + DataServiceQuery in System.Data.Services.Client to hit the Url. 您可以在System.Data.Services.Client使用DataServiceContext + DataServiceQuery来访问Url。 Remember no query is executed until the call to First() due to lazy loading. 请记住,由于延迟加载,在调用First()之前不会执行任何查询。

var context = new DataServiceContext(new Uri("http://odata.org/Product-Service"), DataServiceProtocolVersion.V3);
var query = context.CreateQuery<Product>("Product");
Product product = query.Where(p => p.Id == 150).First();

The above should resolve to http://odata.org/Product-Service/Product(150) which you can check by looking at the query.Entities collection. 以上内容应解析为http://odata.org/Product-Service/Product(150) ,您可以通过查看query.Entities集合进行检查。 Each entity in the collection will contain a Uri. 集合中的每个实体都将包含一个Uri。

Also if your Product class contains a navigation property, you will need to add the expand query option thus: 同样,如果您的Product类包含导航属性,则需要添加扩展查询选项,从而:

var query = context.CreateQuery<Product>("Product").
   AddQueryOption("$expand", "NavigationProperty");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM