Building a .Net Client for ADO.NET Data Service
In the previous post about
ADO.NET data services I
introduced the data services
topic and showed a simple
example of how to build a data service.
In today’s post I’m going to explain how to consume the built data service by
a .NET client.
Revisiting The Previous Post Example
In the previous post I gave an example of course class and course data context.
In the previous example I used the preview version of ADO.NET data service
and since then the VS2008 SP1 was released. The example of the data service
needed to be changed to the new release and the service will look like:
You can see that the only change are the set method and the enum names
which now sets access rules for an entity.
Consume a Data Service With a .Net Client
To consume a data service was made easy in the new SP1 release.
In the previous betas you needed to use the datasvcutil.exe command line
tool in order to generate a proxy for the data service. In the new release
you can use the Add Service Reference like you use it for every other service.
In order to use Add Service Reference you only need to pass the URL of the
data service’s metadata or use the Discover option to discover the service’s
metadata if it’s in your solution.
One thing to remember, if you want to consume the service you need to make
it available by deploying it to IIS or by using the Visual Studio Development Server
with a specific port.
In order to use Visual Studio Development Server you need to go to the
data service project’s properties window and in the Web tab to check the
Specific Port radio button:
Adding Data Service .Net Client to Project
Using the same example from the previous post, I added a new console application
to the solution. In the console application I added a service reference with the
Add Service Reference:
After adding the service in the main method of the console application
I wrote the following code to get all the courses with a 5 credit:
As can be seen in the example I need to give the Uri of the data service
as a parameter to the generated proxy class. Also, as can be seen in the example
data service’s proxy comes with full LINQ capabilities (LINQ to data services)
which enhance the use of data services in a .Net client.
To sum up the post, it’s very easy to consume a data service from a .Net client.
All you need to do is to use the Add Service Reference feature of VS2008 which
will generate a proxy class for you. After you have the proxy in your hands you
can use it to query the data service using LINQ. Other options that you can do
with the proxy are CRUD operations which will be discussed in another post in
the near future.