Search code examples
c#odata

Writing a simple OData client: how to query service?


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.


Solution

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