Introduction
Windows Communication Foundation (WCF) data service exposes data layers in a REST-ful manner and provides a really easy way for AJAX applications and other client-side applications to access the data, without having to go through the effort of writing an entire Web service. This caught my interest to play around with WCF. And through this post, we will see an approach to utilize entity framework and WCF data service to carry out CRUD operation with minimum effort.
REST Basics
Representational state transfer (REST) is a style of software architecture for distributed hypermedia systems such as the World Wide Web. The cool thing about REST is that it is not tied to any particular technology or platform. The term is often used in a looser sense to describe any simple interface which transmits domain-specific data over HTTP without an additional messaging layer such as SOAP or session tracking via HTTP cookies. A RESTFul web service is a simple web service implemented using HTTP and the principles of REST. Such a web service can be thought about as a collection of resources.The MIME type of the data is supported by the web service. This is often JSON , XML or YAML but can be anything. The set of operations are supported by the web service using HTTP methods (e.g. POST
, GET
, PUT
or DELETE
).
WCF Rest Services
WCF Rest Services are normal WCF Services that have added functionality so that they can be consumed in a RESTful manner (URI vs URL, usage of HTTP Verbs, usage of different Data Transfer Formats like JSON, YAML, etc). The table below will help you to understand how the HTTP verbs are typically used to implement a web service.
Method | Description |
---|
GET | Requests a specific representation of a resource |
PUT | Creates or updates a resource with the supplied representation |
DELETE | Deletes the specified resource |
POST | Submits data to be processed by the identified resource |
HEAD | Similar to GET but only retrieves headers and not the body |
OPTIONS | Returns the methods supported by the identified resource |
Configure the WCF Service
It’s time to configure the WCF data service. Though we need entity framework 4 for this example, but I believe configuring entity framework is out of context of this post. So we will stick to configuring WCF data service only. In Solution Explorer, right-click the name of your ASP.NET project, and then click Add New Item. In the Add New Item dialog box, select WCF Data Service.
For the name of the service, I choose EFService.svc. Visual Studio will show you some generated code. You’ll need to add the name of your Entity Framework Data Context in the definition of the WCF Data Service, for this particular example I am using SocialShareDatabaseContext
like below:
public class EFService : DataService<SocialShareDatabaseContext>
Use Visual Studio development server to test the service, which shall be like http://localhost:[port]/EFService.svc/Members //Gets all members. If you open the EFService.svc.cs in the attached sample project, you will see the code below:
Also in web.config, at the bottom you will see 2 sections automatically added, one is: <system.webServer>
and another one is <system.serviceModel>
like below:
Using WCF Rest Services from Client Side
WCF Data Services enable you to provide dynamic access to entity data in an XML format that can be used by applications. You can return XML (default), JSON from WCF REST services. There are a couple of ways to consume REST services from client side, but as a JQuery fan I will stick to it. Before taking the dive, JQuery ajax call requires some parameters that we need to know first, type: type of REST method to invoke, i.e., POST
/GET
/PUT
/DELETE
.
url
: WCF service URL which are called by their URL plus the method name/entity name appended in the URL's extra path data
: Optional parameter, requires if invoking method/entity expects parameter. contentType
: When sending data to the server, use this content-type dataType
: returned data type, i.e. XML, JSON, etc. success
: A function to be called if the request succeeds, REST service will return JSON/XML if successful. error
:A function to be called if the request fails
Now we will see how to invoke the WCF services with different REST methods.
Using GET Method
List the URIs and perhaps other details of the collections. In our case, requests collection of members.
$.ajax({
type: "GET",
url: "Services/EFService.svc/Members",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
},
error: function (msg) {
alert(msg);
}
});
Using POST Method
Retrieve a representation of the addressed member of the collection, in the example below, create a new entry in the collection.
$.ajax({
type: "POST",
url: "Services/EFService.svc/Members/",
data: "{Email:'test@test.com', ScreenName:'TestUser'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
},
error: function (msg) {
alert(msg);
}
});
Using PUT Method
Update the entire collection with another collection, in the example below, update the addressed member of the collection.
$.ajax({
type: "PUT",
url: "Services/EFService.svc/Members/",
data: "{Email:'test@test.com', ScreenName:'TestUser'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
},
error: function (msg) {
alert(msg);
}
});
Using DELETE Method
Delete the entire collection or a specific collection, in the example below, delete Member
with id=1
.
$.ajax({
type: "DELETE",
url: "Services/EFService.svc/Members(1)",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
},
error: function (msg) {
alert(msg);
}
});
Using the Sample Code
Using the attached sample code requires:
- VS2010 with service pack 1 installed
- Microsoft SqlServer 2005 or later
- Basic understanding of Entity Framework 4.0
Configure your environment:
- Attach the sample.mdf and sample.ldf
- Those who want to use sqlserver 2005, download DbSchema-SQLServer2005.zip from top and unzip. Create a database name sample and run the unzipped SQL script
- Open web.config and find
connectionStrings
section and edit the connection string according to your local SQL Server login credential
For tabular data display purposes, I used JQuery template plugin to render collection. Run default.aspx page to see the sample.
History
- Version 1.0: Basic version updated
- Version 1.1: Database schema for Microsoft SqlServer 2005 attached