Introduction to WCF Data service and ODATA

You can see video tutorial of this article

Creating WCF Data Service

Consuming WCF Data Service

WCF Data Service, Project Astoria, OData and ADO.Net Data Service are same thing.


What is ODATA?


· ODATA is HTTP or web protocol to querying or manipulating data.


· ODATA can be implemented through any platform supports, HTTP, XML or JSON.

· ODATA can expose data/information from relational database, File systems, Web sites, services etc.

· ODATA specification available under Microsoft’s Open Specification Promise (OSP) so third parties, including open source projects, can build Open Data Protocol clients and services.

What is WCF Data Service?

· WCF Data service framework provides an API that allows data to be created and consumed over HTTP using RESTful service.

· WCF Data service supports all database operations using URI.

· WCF Data service can expose an entity model via an URI.

· WCF Data service is RESTful service to support CRUD operations on database.

· WCF Data service could be consumed by any type of client like Windows, SilverLight, Web, AJAX and console.


Block diagram explaining working of WCF Data Service


1. Create a Data Access layer using ADO.Net Entity model or LINQ.

2. Make sure Data model is implementing IQueryable and IUpdateable .

3. Expose the data model as REST service using WCF Data service.

CRUD Operations and HTTP verb


Supported Message Format


Sample on WCF Data Service


Let us say, we have a table called Student of below structure below in our data base


In Student table RollNumber is a primary key.

Let us create WCF Data Service which will expose the above table as REST service

Step 1: Create a Web Application

Create a new project and select ASP.Net Web Application project template from Web tab. Give a meaning full name to the web application.


Step 2: Create a Data Model

We can create a Data Model, which can be exposed as WCF Data Service in three ways

1. Using ADO.Net Entity model.

2. Using LINQ to SQL class.

3. Custom Data Model.

For our purpose, I am going to use ADO.Net Entity model to create the data model. So to create an entity model

1. Right click on web application and add a new item

2. Select ADO.Net Entity model from Data tab.


3. Since we have table in data base. so we are going to choose option , select from database.


4. Either choose the data base from drop down or create a new data connection.


In above connection string StudentDBEntities is name of the connection string. If we want, we can change this connection string as per our requirement.

If your required data base is not listed in drop down then, you can create a new data connection. To create new data connection click on New Connection


You can give the data base server name and press refresh. After pressing Refresh, you can choose the data base from the drop down. After selecting the data base click on Test Connection to test connection established successfully or not?

5. Select tables, views and stored procedure from data base you want to make as the part of your data model. Since we are having only one table so we are selecting one table.


If you want you can change name of the data model. By default it is name of the data base appended by the term model. Click on Finish button to complete and create the data model.

6. Now we can see that StudentDataModel.edmx has been created in the designer.


Since there is only one table, so there is only one table model at design surface.

Now we have created the data model which can be exposed as WCF Data Service. Now you can see in solution explorer, you have StudentModel.edmx and StdentModel.Designer.cs files.


Step 3: Creating WCF Data Service

1. Right click on Web Application project and add a new item.

2. Select WCF Data Service from Web tab. Give any meaningful name. I am leaving the default name here.


3. After adding the WCF Data Service, we can see a service file with extension .svc has been added to the solution explorer. When we click on .svc.cs file, we can see the code generated for us.


Very first we need to put data source name. To do so uncomment the first commented line and put the data source name. In our case name of the model, which we created in 2nd step is the data source. Our data source name is StudentDBEntities


Now we need to set access rules for entity or entity set. Since we have only one table, so either we can give name of the table explicitly or if we want to set the same access rule for all the table in the data model or data source we could put *.



So we are setting the access rule that, on the entity in data source perform all the operations.

Step 4: Run the WCF Data Service

Just press F5 to run the WCF Data Service. Data Service will be hosted in the default ASP.Net server called Cassini.

On running you can see, one table is listed. That table is Student


The above is the data in ATOM message format.

Note: If your browser is not showing the expected result, make sure Feed reading of browser is off. To do from menu of IE and select tool and then Internet Option then Content

Img27 Img28


· One feature of WCF data service is that, they provide operation to retrieve Metadata about the service and offer of the service.

· This is very useful in determining structure before requesting them.

· WCF Data service provides metadata accessible.

· Metadata expose all the resource and custom services.

· Metadata could be accessed by appending $metadata to service URI.


So, the URI to access metadata is


URI Query options

We can perform various queries in the browser itself using the URI query options.


Options Descriptions
expand Request set of related entities to be retrieved.
orderby Indicates the sequence entity to be retrieved
skip Skip number of data items.
top At most returns top number of data items
filter Applies the filtering condition


Operators Descriptions
eq Equal
ne Not Equal
gt Greater Than
ge Greate than or equal to
lt Less than
le Less than or equal to
and Logical AND
or Logical OR
not Logical NOT

Math Operators

Operators Descriptions
add add
sub Subtract
mul multiply
div Division
mod remainder

Various queries

1. Fetch all the records from the table Student

URI: http://localhost:29409/WcfDataService1.svc/Students



2. Fetch the student details with roll number 1

URI: http://localhost:29409/WcfDataService1.svc/Students?$filter=RollNumber eq’1′


3. Fetch top 2 record from the student table

URI: http://localhost:29409/WcfDataService1.svc/Students?$top =2


4. Fetch the records of the student with roll number 1 or 3

URI: http://localhost:29409/WcfDataService1.svc/Students?($filter=RollNumber eq’1′)or($filter=rollnumber eq ‘3’)


Different Access rules on the entity set

Enumerator Description
All All Read and Write are permitted
AllRead All Read permitted
AllWrite All Write is permitted
None No access is permitted
ReadMultiple Reading multiple row is permitted
ReadSingle Reading a single row is permitted
WriteAppend Creating New data is permitted
WriteDelete Deleting data is permitted
WriteMerge Merge updating is permitted
WriteReplace Replace updating is permitted

As we discussed above we can set access rule for a particular entity or whole entity set in data source.

config.SetEntitySetAccessRule(“*”, EntitySetRights.All);

This will permit all right access on all entity set.

config.SetEntitySetAccessRule(“Students”, EntitySetRights.AllWrite);

This will permit all write access on Student entity set.

Creating a client to consume WCF Data Service

Step 1

Add a new project in the same solution of type console application.


Step 2

Add the service reference of WCF Data Service. To add right click on the console project and add a service reference. Since WCF Data Service and client project in the same solution , click on Discover to discover the service in the solution.


Add the reference of System.Data.Service.Client in client project also.


Step 3

Add namespaces


Step 4

Need to create instance of DataContext and StudentDBEntities. These two classes take as parameter in their constructor. Parameter is base URI of the WCF Data Service.




Retrieving all the records of table Students


Adding one record in the table Student


Updating a record in the table Student


Delete a record in the table Student


For Reference Full Source Code is here


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using ConsoleClient.ServiceReference1;

using System.Data.Services.Client;

namespace ConsoleClient


class Program


static DataServiceContext context;

static StudentDBEntities studentEntities;

static void Main(string[] args)


context = new DataServiceContext

(new Uri(http://localhost:3803/WcfDataService1.svc/”));

studentEntities = new StudentDBEntities

(new Uri(http://localhost:3803/WcfDataService1.svc/”));

//Get all The Records

foreach (var r in GetAllStudents())





// Insert one Record

AddStudent(new Student() { RollNumber = “100”, Name = “Pinal dave”, Subject = “Sql” });


// Update the Record

UpdateStudent(new Student() { RollNumber = “100”, Name = “KMUG”, Subject = “Sql” });


// Delete the Record


// Get all the Records

foreach (var r in GetAllStudents())






static List<Student> GetAllStudents()


var res = from r in studentEntities.Students select r;

return res.ToList();


static void AddStudent(Student std)


context.AddObject(“Students”, std);


// Other way

//Student std1 = new Student() { RollNumber = “9999”,

//    Name = “Pinale Dave”,

//    Subject = “SQL Server” };




static void UpdateStudent(Student std)


Student stdtoUpdate = (from r in studentEntities.Students

where r.RollNumber == std.RollNumber

select r).First();

stdtoUpdate.Name = std.Name;

stdtoUpdate.Subject = std.Subject;

context.AttachTo(“Students”, stdtoUpdate);



// Other way to Update

// studentEntities.UpdateObject(stdtoUpdate);



static void DeleteStudent(string stdRollNo)


Student stdtoUpdate = (from r in studentEntities.Students

where r.RollNumber == stdRollNo

select r).First();

//context.AttachTo(“Students”, stdtoUpdate);



//Other way






I hope this article was useful. Thanks for reading. Happy Coding.

17 responses to “Introduction to WCF Data service and ODATA”

  1. Nice post Dhananjay.

  2. thanking you dhananjay

  3. Vijay Kumar Raju

    Article is pretty good.

    Your comment “make sure Feed reading of browser is off” is of very helpfull. I have wasted almost one day not knowing this.

    By Checking “Feed reading of browser”, it is listing down number of records but no info is available. But when I see View Source, all the XML is available. I don’t understand the purpose of that option in IE. Please let me know if you have any idea

  4. […] you are new to this topic, please read Introduction to WCF Data service and ODATA before going through below […]

  5. […] you are new to this topic, please read Introduction to WCF Data service and ODATA before going through below […]

  6. thx
    very helpfull one .

  7. Nice Post, Can tell me one thing. If my entities are built form a combination of tables and references a View. How can i use the updateobject to multiple tables as the entity exposed is only view.

  8. Where can I get the StudentDB!?

  9. Simply awesome!!! Thanks

  10. prabhjot singh bakshi

    worth every line …… May GOD bless you.
    prabhjot singh Bakshi

  11. […] Introduction to WCF Data service and ODATA Posted on Saturday, 25 December 2010 by Dhananjay kumar No Comment var addthis_pub="izwan00"; BOOKMARK Autor :  Dhananjay Kumar […]

  12. […] You can read Introduction to WCF Data service and ODATA here […]

  13. Been searching for days for a clear and concise example of CRUD on the Client side. All the tutorials out there that are worth anything are all AJAX based tutorials. Awesome Job!!!!

  14. Thank you very much, very clear and easy. You help me a lot.
    God Bless You!

  15. I’ll immediately snatch your rss as I can’t in finding
    your e-mail subscription hyperlink or newsletter
    service. Do you’ve any? Kindly let me recognise so that I may just subscribe. Thanks.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at