Writing a simple OData client: how to query servic

2019-08-03 17:47发布

I am trying to adapt this example to create a simple OData client. Before that, I added a service reference in Visual Studio to "http://services.odata.org/Northwind/Northwind.svc/".

By this step I got many classes like "Alphabetical_list_of_product". But how do I get the alphabetical list of products, for example?

Specifically, in the example the author just starts with:

OdataClient.NorthwindOdataService.NorthwindEntities dc = 
    new OdataClient.NorthwindOdataService.NorthwindEntities(
        new Uri("http://services.odata.org/Northwind/Northwind.svc/")); 

But where did he get the OdataClient.NorthwindOdataService.NorthwindEntities class from?

I am new to web services and OData, so apologies if the question is vague.

标签: c# odata
2条回答
闹够了就滚
2楼-- · 2019-08-03 18:08

If you want a client for consuming OData service, a good choice should be OData code generator. You can start by reading the tutorial http://blogs.msdn.com/b/odatateam/archive/2014/03/12/how-to-use-odata-client-code-generator-to-generate-client-side-proxy-class.aspx .

查看更多
爷的心禁止访问
3楼-- · 2019-08-03 18:17

Here is an example of how the service reference can be used after it has been added to the project:

// Create a service context object
// "NorthwindEntities" is the name of the class in the generated service reference that derives DataServiceContext
// The URI in should be the same URI you used to add the service reference
var context = new NorthwindEntities(new Uri("http://services.odata.org/Northwind/Northwind.svc/"));

// As Alphabetical_list_of_products is an entity set, it can be directly called from the context
// Call Execute() finally to send the request to the OData service and materialize the response got to "products"
var products = context.Alphabetical_list_of_products.Execute();

// Iterate through all the products and print "ProductName", which is the name of a property on "Alphabetical_list_of_product" entity
foreach (var product in products)
{
    Console.WriteLine(product.ProductName);
}

As you are new to OData, it is recommended that you start from OData V4. Add Service Reference supports client side proxy generation of OData service up to OData V3. The OData V4 protocol on OASIS Comittee and the blog of the OData team of Microsoft can be referred to for details.

查看更多
登录 后发表回答