How to create query expression for Odata for get by Id

北慕城南 提交于 2019-12-12 08:57:47

问题


I have created an OData service and now I am trying to consume this service at client side. I wants to create an expression such as for the below url in the c# query expression-

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. Any help would be greatly appreciable.


回答1:


You could use a DataServiceContext + DataServiceQuery in System.Data.Services.Client to hit the Url. Remember no query is executed until the call to First() due to lazy loading.

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. Each entity in the collection will contain a Uri.

Also if your Product class contains a navigation property, you will need to add the expand query option thus:

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


来源:https://stackoverflow.com/questions/23493451/how-to-create-query-expression-for-odata-for-get-by-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!