Gal Ratner
Gal Ratner is a Techie who lives and works in Los Angeles CA and Austin TX. Follow galratner on Twitter Google
Consume an OData WCF Data Service as JSON with JQuery

OData(Open Data Protocol) is an HTTP based protocol for querying and updating data using full REST syntax. The full specifications of OData can be found on http://odata.org


WCF Data Services (formerly ADO.NET Data Services, formerly Project Astoria) is the .NET based implementation of OData enabled services. WCF Data Services can use an Entity Framework Context or any data model exposing at least one property that returns an entity set that is an IQueryable(Of T). The model must also implement IUpdatable.


A sample http request to an OData service will look like:
http://services.odata.org/OData/OData.svc/Categories(1)/Products?$skip=2


This example will get the products associated with the category identified by key value 1, starting with the third product.


WCF Data Services is capable of returning data in multiple formats. The default format will be set based on the requesting client’s accept request header with an option to override the format using the $format query option.  For example, this will return the results from the previous example in JSON format:
http://services.odata.org/OData/OData.svc/Categories(1)/Products?$skip=2&$format=json


Currently supported formats and their matching accept request headers

•    Atom: application/atom+xml
•    Xml: application/xml
•    Json: application/json


In this article we are going to create a new WCF Data Service, use a code first Entity Framework model and consume a JSON feed using JQuery.

The ET Model we are using is the same model used in my article http://galratner.com/blogs/net/archive/2011/03/24/four-ways-to-utilize-entity-framework-4.aspx with a slight change; since the service invokes the model’s default constructor we are going to make sure our string connection is set in the process. The updated model looks like this:

 

public class EFExampleDbContext : DbContext
    {
        public EFExampleDbContext()
            : base("EFExampleEntitiesStringConnection")
        {
 
        }
 
        public EFExampleDbContext(string nameOrConnectionString)
            : base(nameOrConnectionString)
        {
 
        }
        
        public DbSet<Customer> Customers { getset; }
        public DbSet<Order> Orders { getset; }
    }



Now let’s create a new WCF Data Service and set the appropriate permissions on our entity sets:

 

public class CustomersDataService : DataService<EFExampleDbContext>
    {
        public static void InitializeService(DataServiceConfiguration config)
        {
            config.SetEntitySetAccessRule("Customers"EntitySetRights.AllRead);
            config.SetEntitySetAccessRule("Orders"EntitySetRights.AllRead);
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
        }
    }


The last step will be to query our service from the client. Let’s use JQuery’s getJSON method since it internally sets the accept request header to application/json.

 

<script>
    $.getJSON("CustomersDataService.svc/Customers",
  function (data) {
      $.each(data.d, function (i, item) {
          $("<p/>").html(item.FirstName + " " + item.LastName).appendTo("#myData");
      });
  });
 </script>

 

<div id="myData"></div>



This will query our CustomersDataService for all of our customers, get the response in JSON format and display the data in the #myData div.


Conclusion
OData can be a very flexible and powerful protocol when used to retrieve and update data from multiple clients using a single data model on the server. There are many open source client projects and Javascript helper libraries with a full list on http://odata.org. OData is widely adopted including support in RIA services, Share point and more. If you are planning to syndicate content over HTTP WCF Data Services might be your preferred option.

Shout it


Posted 14 Apr 2011 9:34 PM by Gal Ratner
Filed under: ,

Powered by Community Server (Non-Commercial Edition), by Telligent Systems