Consuming OData Based Rest Service in C#

Consuming OData Based Rest Service in C#

Nowadays comunication between applications is an active topic with daily usage and a large amount of pratical appliances. While developing an app in witch I had to consume an OData I found out that combining Linq with my code made this operation pretty easy.

The algorithm to consume OData starts with adding a service reference to Visual Studio:

image

After adding the service reference in which you define the uri to the service, we start building our code.

In your code the algorithm is the following:

  1. Define the Uri to your OData Service
  2. Define the context of your odata, which contains all entities exposed by the service.
  3. Query the context using Linq
  4. Print the result

Easy and simple.

Example code

 
public static void Main(string[] args){

        Uri serviceUri= new Uri("http://example.host.odataservice.net/service.svc", UriKind.Absolute);
        ODataService.ServiceEntities context = new ODataService.ServiceEntities (serviceUri);

        context.Credentials = new System.Net.NetworkCredential(Username,Password);

         var query = from ServiceObject in context.YourEntity
                     select ServiceObject ;

        foreach (var myObject in query)
        {
            Console.WriteLine("\n Field1: {0} | Field2: {1}",
            myObject .Field1, myObject .Field2);

        }
}

 

That’s it.

Thank you,

Rui Machado

rpmachado.wordpress.com

Leave a Comment
  • Please add 3 and 4 and type the answer here:
  • Post
Wiki - Revision Comment List(Revision Comment)
Sort by: Published Date | Most Recent | Most Useful
Comments
  • Ed Price - MSFT edited Revision 5. Comment: tag

  • Richard Mueller edited Revision 3. Comment: Replaced "rgb(255, 192, 0)" with "gold" in HTML to restore the color

  • Richard Mueller edited Revision 2. Comment: Modified title casing, removed (en-US) from title

Page 1 of 1 (3 items)
Wikis - Comment List
Sort by: Published Date | Most Recent | Most Useful
Posting comments is temporarily disabled until 10:00am PST on Saturday, December 14th. Thank you for your patience.
Comments
  • Richard Mueller edited Revision 2. Comment: Modified title casing, removed (en-US) from title

  • Richard Mueller edited Revision 3. Comment: Replaced "rgb(255, 192, 0)" with "gold" in HTML to restore the color

  • Carsten Siemens edited Revision 4. Comment: fixed typo

  • good job

  • Ed Price - MSFT edited Revision 5. Comment: tag

Page 1 of 1 (5 items)