Oh, Data!

Open Data (aka OData) is a new standard for exchanging data using REST-like services. The idea is you can get access to data using the same standard regardless of what server / data source you’re talking to. For example, let’s say I want a certain comment for a certain blog post – I shouldn’t have to type anything more than “service.svc/Posts(23)/Comments(123)” and it’ll work. The standard itself defines how specific records or collections are accessed, as well as conventions for paging, sorting, etc. that should be followed by every OData source.

And of course, Microsoft has gone out of their way to make this incredibly easy for developers to implement. Given a data context (i.e. one that would be created using LinQ to SQL or Entity Framework), all you need is:

public class Service : DataService<MyBlogDataContext>
    // This method is called only once to initialize service-wide policies.
    public static void InitializeService(DataServiceConfiguration config)
        config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);

That’s it. DataService is the base class provided as part of WCF that lets you define a context of data you want to share out, and you specify a few options in the overridden “InitializeService” method, and you’re good to go. This will automatically serve out your data based on the URL in either Atom, XML or JSON. Of course there’s more stuff you can add for configuration, paging, caching, rights management, etc., but if you just want a read-only service with default values you’re done. So what does this actually get you? Well, besides a standardized RESTful service, there’s a lot of benefits if you’re just dealing with handing out data. Here’s a few scenarios:

Request URL
List of catalogs http://localhost/service.svc
List of Posts http://localhost/service.svc/Posts
Specific Post (ID = 12) http://localhost/service.svc/Posts(12)
All comments for Specific Post http://localhost/service.svc/Posts(12)?$expand=Comments
User record of the person who made the a comment on a post http://localhost/service.svc/Posts(12)/Comments(123)/User
Filter posts where title contains “SQL” http://localhost/service.svc/Posts?$filter=substringof(“SQL”,Title)
Number of posts with filter http://localhost/service.svc/Posts?$filter=substringof(“SQL”,Title)/$count
Order posts by votes descending http://localhost/service.svc/Posts?$orderby=Votes desc
Top 5 results, skipping first 2 http://localhost/service.svc/Posts?$filter=substringof(“SQL”,Title)&$top=5&$skip=2
All posts where votes are greater than 10 http://localhost/service.svc/Posts?$filter=Votes gt 10
Only the title and date of each post http://localhost/service.svc/Posts?$select=Title,Date

Remember when we used to have to code all of that?