Skip to content

Latest commit

 

History

History
221 lines (123 loc) · 12.2 KB

calling-an-odata-service-from-a-net-client.md

File metadata and controls

221 lines (123 loc) · 12.2 KB
uid title author description ms.author ms.date ms.assetid msc.legacyurl msc.type
web-api/overview/odata-support-in-aspnet-web-api/odata-v3/calling-an-odata-service-from-a-net-client
Calling an OData Service From a .NET Client (C#) | Microsoft Docs
rick-anderson
This tutorial shows how to call an OData service from a C# client application. Software versions used in the tutorial Visual Studio 2013 (works with Visual S...
riande
02/26/2014
6f448917-ad23-4dcc-9789-897fad74051b
/web-api/overview/odata-support-in-aspnet-web-api/odata-v3/calling-an-odata-service-from-a-net-client
authoredcontent

Calling an OData Service From a .NET Client (C#)

by Mike Wasson

Download Completed Project

This tutorial shows how to call an OData service from a C# client application.

Software versions used in the tutorial

In this tutorial, I'll walk through creating a client application that calls an OData service. The OData service exposes the following entities:

  • Product
  • Supplier
  • ProductRating

Diagram showing the O Data service entities and a list of their properties, with connecting arrows to show how each relate or work together.

The following articles describe how to implement the OData service in Web API. (You don't need to read them to understand this tutorial, however.)

Generate the Service Proxy

The first step is to generate a service proxy. The service proxy is a .NET class that defines methods for accessing the OData service. The proxy translates method calls into HTTP requests.

Diagram showing the service proxy's H T T P request calls running back and forth from the application, through the service proxy, and to the O Data service.

Start by opening the OData service project in Visual Studio. Press CTRL+F5 to run the service locally in IIS Express. Note the local address, including the port number that Visual Studio assigns. You will need this address when you create the proxy.

Next, open another instance of Visual Studio and create a console application project. The console application will be our OData client application. (You can also add the project to the same solution as the service.)

Note

The remaining steps refer the console project.

In Solution Explorer, right-click References and select Add Service Reference.

Screenshot of the solution explorer window, showing the menu under 'references' in order to add a new service reference.

In the Add Service Reference dialog, type the address of the OData service:

[!code-consoleMain]

where port is the port number.

Screenshot of the 'add service reference' window, which shows the port number in the U R L address field and a field to add a Name space.

For Namespace, type "ProductService". This option defines the namespace of the proxy class.

Click Go. Visual Studio reads the OData metadata document to discover the entities in the service.

Screenshot of the 'add service reference' dialog box, highlighting the container service, to show the operations running in it.

Click OK to add the proxy class to your project.

Screenshot of the solution explorer dialog box, showing the menu under the 'product service client' and highlighting the option for 'Product Service'.

Create an Instance of the Service Proxy Class

Inside your Main method, create a new instance of the proxy class, as follows:

[!code-csharpMain]

Again, use the actual port number where your service is running. When you deploy your service, you will use the URI of the live service. You don't need to update the proxy.

The following code adds an event handler that prints the request URIs to the console window. This step isn't required, but it's interesting to see the URIs for each query.

[!code-csharpMain]

Query the Service

The following code gets the list of products from the OData service.

[!code-csharpMain]

Notice that you don't need to write any code to send the HTTP request or parse the response. The proxy class does this automatically when you enumerate the Container.Products collection in the foreach loop.

When you run the application, the output should look like the following:

[!code-consoleMain]

To get an entity by ID, use a where clause.

[!code-csharpMain]

For the rest of this topic, I won't show the entire Main function, just the code needed to call the service.

Apply Query Options

OData defines query options that can be used to filter, sort, page data, and so forth. In the service proxy, you can apply these options by using various LINQ expressions.

In this section, I'll show brief examples. For more details, see the topic LINQ Considerations (WCF Data Services) on MSDN.

Filtering ($filter)

To filter, use a where clause. The following example filters by product category.

[!code-csharpMain]

This code corresponds to the following OData query.

[!code-consoleMain]

Notice that the proxy converts the where clause into an OData $filter expression.

Sorting ($orderby)

To sort, use an orderby clause. The following example sorts by price, from highest to lowest.

[!code-csharpMain]

Here is the corresponding OData request.

[!code-consoleMain]

Client-Side Paging ($skip and $top)

For large entity sets, the client might want to limit the number of results. For example, a client might show 10 entries at a time. This is called client-side paging. (There is also server-side paging, where the server limits the number of results.) To perform client-side paging, use the LINQ Skip and Take methods. The following example skips the first 40 results and takes the next 10.

[!code-csharpMain]

Here is the corresponding OData request:

[!code-consoleMain]

Select ($select) and Expand ($expand)

To include related entities, use the DataServiceQuery<t>.Expand method. For example, to include the Supplier for each Product:

[!code-csharpMain]

Here is the corresponding OData request:

[!code-consoleMain]

To change the shape of the response, use the LINQ select clause. The following example gets just the name of each product, with no other properties.

[!code-csharpMain]

Here is the corresponding OData request:

[!code-consoleMain]

A select clause can include related entities. In that case, do not call Expand; the proxy automatically includes the expansion in this case. The following example gets the name and supplier of each product.

[!code-csharpMain]

Here is the corresponding OData request. Notice that it includes the $expand option.

[!code-consoleMain]

For more information about $select and $expand, see Using $select, $expand, and $value in Web API 2.

Add a New Entity

To add a new entity to an entity set, call AddToEntitySet, where EntitySet is the name of the entity set. For example, AddToProducts adds a new Product to the Products entity set. When you generate the proxy, WCF Data Services automatically creates these strongly-typed AddTo methods.

[!code-csharpMain]

To add a link between two entities, use the AddLink and SetLink methods. The following code adds a new supplier and a new product, and then creates links between them.

[!code-csharpMain]

Use AddLink when the navigation property is a collection. In this example, we are adding a product to the Products collection on the supplier.

Use SetLink when the navigation property is a single entity. In this example, we are setting the Supplier property on the product.

Update / Patch

To update an entity, call the UpdateObject method.

[!code-csharpMain]

The update is performed when you call SaveChanges. By default, WCF sends an HTTP MERGE request. The PatchOnUpdate option tells WCF to send an HTTP PATCH instead.

Note

Why PATCH versus MERGE? The original HTTP 1.1 specification (RCF 2616) did not define any HTTP method with "partial update" semantics. To support partial updates, the OData specification defined the MERGE method. In 2010, RFC 5789 defined the PATCH method for partial updates. You can read some of the history in this blog post on the WCF Data Services Blog. Today, PATCH is preferred over MERGE. The OData controller created by the Web API scaffolding supports both methods.

If you want to replace the entire entity (PUT semantics), specify the ReplaceOnUpdate option. This causes WCF to send an HTTP PUT request.

[!code-csharpMain]

Delete an Entity

To delete an entity, call DeleteObject.

[!code-csharpMain]

Invoke an OData Action

In OData, actions are a way to add server-side behaviors that are not easily defined as CRUD operations on entities.

Although the OData metadata document describes the actions, the proxy class does not create any strongly-typed methods for them. You can still invoke an OData action by using the generic Execute method. However, you will need to know the data types of the parameters and the return value.

For example, the RateProduct action takes parameter named "Rating" of type Int32 and returns a double. The following code shows how to invoke this action.

[!code-csharpMain]

For more information, seeCalling Service Operations and Actions.

One option is to extend the Container class to provide a strongly typed method that invokes the action:

[!code-csharpMain]