Accessing WCF Data Services from ASP.NET applications
Posted: (EET/GMT+2)
WCF Data Services (previously called ADO.NET Data Services) is a very nice technology that allows you to publish a data source (such as an SQL Server database) to the Internet using the HTTP/HTTPS protocols. Data can be retrieved in multiple formats, by default in Atom-based XML format.
So far, all material that I've seen has been discussing WCF Data Services along with Silverlight applications. However, nobody said that WCF Data Services could not be used to supply data to a (distributed) ASP.NET web application, whether using WebForms or MVC.
Of course, the need to use WCF Data Services from ASP.NET applications is more limited because usually, both the web application and the SQL database are running if not on the same server, on the same LAN at least, which allows the ASP.NET application to access the database directly. But, this is not always the case.
Here's a quick rundown on how to access your WCF Data Services. First, you need to create your WCF Data Service server part normally (check out this tutorial or my previous screencast for tips). Alternatively, you could use the demo endpoint at http://services.odata.org/Northwind/Northwind.svc/ to retrieve ready-made Northwind data.
After you have the URL for the exposed WCF Data Service endpoint, create your intermediate ASP.NET web application, and add a service reference to this endpoint. You should now have access to the data source objects, such as NorthwindEntities and the accompanying database tables.
At this point, it's only a matter of using the created entities object to access the data. For example, to retrieve data using LINQ, you could simply use the data source much in the same way you would use ADO.NET Entity Framework, for instance. Here's a quick example using the synchronous method:
string url = "http://services.odata.org/Northwind/Northwind.svc/";NorthwindEntities entities =
new NorthwindEntities(new Uri(url));
var finnishCusts = from c in entities.Customers
where c.Country == "Finland"
select c;
GridView1.DataSource = finnishCusts;
GridView1.DataBind();
As you can see, it could not get much easier than this. The bottom line is that a WCF Data Service can be added to your "client" project (whether a real client like a Silverlight application or an ASP.NET web application) just like any other service reference would.