简体   繁体   中英

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. 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.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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