Create an OData v4 Client App (C#)

by Mike Wasson

In the previous tutorial, you created a basic OData service that supports CRUD operations. Now let's create a client for the service.

Start a new instance of Visual Studio and create a new console application project. In the New Project dialog, select Installed > Templates > Visual C# > Windows Desktop, and select the Console Application template. Name the project "ProductsApp".

Screenshot of the new project dialog box, highlighting the path through the menu options, to create a new console application project.

Note

You can also add the console app to the same Visual Studio solution that contains the OData service.

Install the OData Client Code Generator

From the Tools menu, select Extensions and Updates. Select Online > Visual Studio Gallery. In the search box, search for "OData Client Code Generator". Click Download to install the VSIX. You might be prompted to restart Visual Studio.

Screenshot of the extensions and updates dialog box, showing the menu for downloading and installing the V S I X client code generator for O Data.

Run the OData Service Locally

Run the ProductService project from Visual Studio. By default, Visual Studio launches a browser to the application root. Note the URI; you will need this in the next step. Leave the application running.

Screenshot of the web browser's local host, showing the code of the Product Service project that is running on visual studio.

Note

If you put both projects in the same solution, make sure to run the ProductService project without debugging. In the next step, you will need to keep the service running while you modify the console application project.

Generate the 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. You will create the proxy class by running a T4 template.

Right-click the project. Select Add > New Item.

Screenshot of the solution explorer dialog box, showing the file path for adding a new item to the project, by highlighting the options in yellow.

In the Add New Item dialog, select Visual C# Items > Code > OData Client. Name the template "ProductClient.tt". Click Add and click through the security warning.

Screenshot of the new items product app settings window, showing the O Data client product template, and circling the name field below to add new name.

At this point, you'll get an error, which you can ignore. Visual Studio automatically runs the template, but the template needs some configuration settings first.

Screenshot of the error message window, showing one error tab and one warning tab, along with a detailed message of the error.

Open the file ProductClient.odata.config. In the Parameter element, paste in the URI from the ProductService project (previous step). For example:

<Parameter Name="MetadataDocumentUri" Value="http://localhost:61635/" />

Screenshot of the product client O Data dot config file, showing an example of the U R I after being pasted in the parameter element.

Run the template again. In Solution Explorer, right click the ProductClient.tt file and select Run Custom Tool.

The template creates a code file named ProductClient.cs that defines the proxy. As you develop your app, if you change the OData endpoint, run the template again to update the proxy.

Screenshot of the solution explorer window menu, highlighting the product client dot c s file that was created, which defines the proxy.

Use the Service Proxy to Call the OData Service

Open the file Program.cs and replace the boilerplate code with the following.

using System;

namespace ProductsApp
{
    class Program
    {
        // Get an entire entity set.
        static void ListAllProducts(Default.Container container)
        {
            foreach (var p in container.Products)
            {
                Console.WriteLine("{0} {1} {2}", p.Name, p.Price, p.Category);
            }
        }

        static void AddProduct(Default.Container container, ProductService.Models.Product product)
        {
            container.AddToProducts(product);
            var serviceResponse = container.SaveChanges();
            foreach (var operationResponse in serviceResponse)
            {
                Console.WriteLine("Response: {0}", operationResponse.StatusCode);
            }
        }

        static void Main(string[] args)
        {
            // TODO: Replace with your local URI.
            string serviceUri = "http://localhost:port/";
            var container = new Default.Container(new Uri(serviceUri));

            var product = new ProductService.Models.Product()
            {
                Name = "Yo-yo",
                Category = "Toys",
                Price = 4.95M
            };

            AddProduct(container, product);
            ListAllProducts(container);
        }
    }
}

Replace the value of serviceUri with the service URI from earlier.

// TODO: Replace with your local URI.
string serviceUri = "http://localhost:port/";

When you run the app, it should output the following:

Response: 201
Yo-yo 4.95 Toys