This week we started investigating OData and WCF data services as a way to easily expose and query a remote database.
OData, the Open Data Protocol is a protocol for querying and updating data over using Http and AtomPub
Visual studio 2010 and .NET 4.0 come with rich support to both produce and consume data using the Open Data Protocol.
This post is a tutorial on how to set up a web service that exposes OData, and how to query it from a client application.
Prerequisites
- Visual Studio 2010
- .NET 4.0 Framework or the Data Services update for Microsoft .NET Framework 3.5 Service Pack 1
Exposing data as Odata
Create a new ASP.NET Web application
Create the Entity Data Model for the Northwind database
The Entity Data Model will be the base for the WCF Data Service that will expose the Northwind data in the OData format
Here we can choose which Tables, Views and Stored Procedures will be exposed
Finish creates the Entity Data Model for the Northwind database
Create a new WCF Data Service
The NorthwindService inherits from the DataService with as generic parameter the EntityDataModel we want to expose, in this case the NorthwindEntities we just created.
By default noone can do anything, we first need to set access rules for our entities.
The easyest way to do this is to expose all entities with read-all rights:
config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
If the Entity Data Model is in a different assembly you’ll need to add a reference, and make sure the connectionstring is in the web.config of the referencing project
Visiting the service now shows the exposed data:
Consuming the data
To use the data exposed by the web service we create a client application.
Add a Service Reference to the web service.
For testing, there is always a public Northwind web service available on http://services.odata.org/Northwind/Northwind.svc/
This generates a web service proxy.
New is that this also generates a DataServiceContext.
Using the DataServiceContext we can query the data service through a linq provider.
The following extremely simple example print a list with the Name and Unit Price of all available products.
class Program
{
static void Main(string[] args)
{
string url = "http://localhost:40171/NorthwindService.svc/";
var context = new NorthwindEntities(new Uri(url));
var someProducts = from p in context.Products
where !p.Discontinued
select p;
foreach (var product in someProducts)
{
Console.Out.WriteLine("{0} - {1}",product.ProductName,product.UnitPrice);
}
Console.Read();
}
}
Download the sample code:
http://www.orbitone.com/SiteCollectionDocuments/Northwind%20OData%20Service%20Sample.zip
More information, samples, articles and tutorials can be found on http://www.odata.org/
Some more links to get you started: