A basic introduction to creation of CRUD operation using OData Web Service via WCF Data Services

Niladri.Biswas
Posted by in WCF category on for Beginner level | Points: 250 | Views : 21393 red flag
Rating: 5 out of 5  
 1 vote(s)

In this article we will have a basic introduction to creation of CRUD operation using OData Web Service via WCF Data Services


 Download source code for A basic introduction to creation of CRUD operation using OData Web Service via WCF Data Services

Introduction

WCF Data Services is a part of the .NET Framework that provides the ability to create Windows Communication Foundation (WCF) services that use the Atom Publishing protocol (AtomPub) and Open Data protocol (OData) to expose and consume data over the web.WCF data Services are a new feature in .net 4 framework.It exposes data by using the semantics of representational state transfer(REST). OData provides the ability to perform create, retrieve, update, and delete (CRUD) operations and can be used on a variety of sources such as relational databases, file systems,content management systems, and traditional websites.

WCF Data Services provides an easy mean of enabling clients to use backend functionalities on databases residing on the server side.It creates a cloud based interface service layer juxtaposed between the client and the Entity Data Model(EDM) which on the other hand interacts with the database.We can use LINQ to SQL or LINQ to Entities for the EDM.

Steps to create WCF Data Services

In this article we will look into the basic CRUD operation for Employee Entity by using WCF Data services in a step by step manner.We will make a simple Employee Database and will employe the needed operations based on the Employee model.

Step 1:Table creation

Let us first create the Employee table

USE [YourDatabase Name]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Employee]') AND type in (N'U'))
DROP TABLE [dbo].[Employee]
GO
CREATE TABLE [dbo].[Employee](
[EmpId] [int] IDENTITY(1,1) NOT NULL,
[EmpName] [varchar](100) NULL,
[EmpAge] [int] NULL,
[EmpSalary] [decimal](10, 2) NULL,
[DOB] [datetime] NULL,
CONSTRAINT [PK_EmpId] PRIMARY KEY CLUSTERED
(
[EmpId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Step 2:Make the Web Project

First of all create a solution file(say WCFDataServiceSolution).Add a new Asp.net Web Application (say WCFDataServiceSite) to the solution.

And make the design by the below code

<html>

<head runat="server">

<title></title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:Panel ID="pnlInsertEmpRecord" runat="server">

<h2>

Insert Employee Information</h2>

<table>

<tr>

<td>

Employee Name:

</td>

<td>

<asp:TextBox ID="txtEmpName" runat="server"></asp:TextBox>

</td>

<td>

Employee Age:

</td>

<td>

<asp:TextBox ID="txtEmpAge" runat="server"></asp:TextBox>

</td>

</tr>

<tr>

<td>

Employee Salary:

</td>

<td>

<asp:TextBox ID="txtSalary" runat="server"></asp:TextBox>

</td>

<td>

Employee DOB:

</td>

<td>

<asp:TextBox ID="txtDOB" runat="server"></asp:TextBox>

</td>

</tr>

<tr>

<td colspan="4">

<asp:Button ID="btnInsert" runat="server" Text="Insert record" OnClick="btnInsert_Click" />

</td>

</tr>

<tr>

<td colspan="4">

<asp:Label runat="server" ID="lblSuccessMsg"></asp:Label>

</td>

</tr>

</table>

</asp:Panel>

<asp:Panel ID="pnlDisplayEmpRecord" runat="server">

<h2>

View Employee Information</h2>

<table>

<tr>

<td colspan="2">

<asp:GridView ID="grdView" runat="server" AutoGenerateColumns="false">

<Columns>

<asp:TemplateField HeaderText="Select" ItemStyle-Width="2%">

<ItemTemplate>

<asp:CheckBox ID="chkSel" runat="Server"/>

</ItemTemplate>

</asp:TemplateField>

<asp:BoundField DataField="EmpId" HeaderText="Id" ItemStyle-Width="6%" />

<asp:TemplateField HeaderText="Name" ItemStyle-Width="2%">

<ItemTemplate>

<asp:TextBox ID="txtEmployeeName" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"EmpName") %>'></asp:TextBox>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Age" ItemStyle-Width="2%">

<ItemTemplate>

<asp:TextBox ID="txtEmployeeAge" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"EmpAge") %>'></asp:TextBox>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="Salary" ItemStyle-Width="2%">

<ItemTemplate>

<asp:TextBox ID="txtEmployeeSalary" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"EmpSalary") %>'></asp:TextBox>

</ItemTemplate>

</asp:TemplateField>

<asp:TemplateField HeaderText="DOB" ItemStyle-Width="2%">

<ItemTemplate>

<asp:TextBox ID="txtEmployeeDOB" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"DOB") %>'></asp:TextBox>

</ItemTemplate>

</asp:TemplateField>

</Columns>

</asp:GridView>

</td>

</tr>

<tr>

<td>

<asp:Button ID="btnUpdate" runat="server" Text="Update record"

onclick="btnUpdate_Click" />

</td>

<td>

<asp:Button ID="btnDelete" runat="server" Text="Delete record"

onclick="btnDelete_Click" />

</td>

</tr>

</table>

</asp:Panel>

</div>

</form>

</body>

</html>

The output will be

Step 3:Make the Entity Data Model

Then choose EntityDataModel template from the list of available templates.

Click on "Add" button.Choose "Generate from Database" as the model from the "Choose Model Contents" screen and click on the "Next Button".

The next screen that appears is the "Choose your Data Connection" where we need to enter the proper connection.Once done (i.e. the Test Connection succeeds), eneter "WCFDataServiceEntities" in the "Save Entity Connection Settings in App.Config as" textbox.Also choose "Yes, include sensitive data in the connection string" radiobutton.And then click on the "Next" button.

The "Choose your Database object" screen appears.In this screen, choose "Employee" from the Tables object.And lastly click on the "Finish" button.

Step 4:Make the WCF DataService

Now select the "WCFDataServiceSite" project.Right click ->Add New Item.Next choose the "WCF Data Service" template from the web node.Let us name it as "EmployeeDataService.svc" and click on "Add" button.

After this let us open the "EmployeeDataService.svc.cs" file and we will find that two "TODO" comments are generated to direct our attention to code that needs to be changed for the service to be operable

Put the "WCFDataServiceEntities" in the

 DataService<WCFDataServiceEntities>
and put "*" in

config.SetEntitySetAccessRule("*", EntitySetRights.All);

The use of "*" character indicates that we want to include all the tables in the entity set."EntitySetRights.All" ensures authorization to create, read, update, and delete data.So the code will now look as under

using System.Data.Services;

using System.Data.Services.Common;

using WCFDataServiceDal;

 

namespace WCFDataServiceSite

{

public class EmployeeDataService : DataService<WCFDataServiceEntities>

{

// This method is called only once to initialize service-wide policies.

public static void InitializeService(DataServiceConfiguration config)

{

// TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.

// Examples:

config.SetEntitySetAccessRule("*", EntitySetRights.All);

// config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All);

config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;

}

}

}

The next step will be to locate our service and add it to the project

N.B.~It is important to note the address as it will be needed at a later stage

Step 5:Bind the data to the grid(READ operation)

Let us look at the below code

protected void Page_Load(object sender, EventArgs e)

{

Uri myUri = new Uri("http://localhost:51637/EmployeeDataService.svc");

var client = new EmployeeDataServiceClient.WCFDataServiceEntities(myUri);

grdView.DataSource = client.Employees.ToList();

grdView.DataBind();

}

We are passing the "Uri" inorder to get the record from the respected source that we are binding to the gridview control.The final output is as under

Step 6:Insert Data(CREATE operation)

Let us look at the below code

Uri myUri = new Uri("http://localhost:51637/EmployeeDataService.svc");
var client = new EmployeeDataServiceClient.WCFDataServiceEntities(myUri);

EmployeeDataServiceClient.Employee emp = new EmployeeDataServiceClient.Employee();
emp.EmpName = txtEmpName.Text;
emp.EmpAge = Convert.ToInt32(txtEmpAge.Text);
emp.EmpSalary = decimal.Parse(txtSalary.Text, CultureInfo.InvariantCulture);
emp.DOB = Convert.ToDateTime(txtDOB.Text);

//Add the record to the employee collection
client.AddToEmployees(emp);

//Save the changes
client.SaveChanges();

In this case we first find the "Employee" entity and assign the new values to it.Then we add it to the Employees collection by using the "AddToEmployees" method.And finally, we save the changes.Once the record has been inserted properly, the system will update the same with a positive response.

Step 7:Update Data(UPDATE operation)

Let us look at the below code

Uri myUri = new Uri("http://localhost:51637/EmployeeDataService.svc");

var client = new EmployeeDataServiceClient.WCFDataServiceEntities(myUri);

var grvRecord = grdView.Rows.Count;

 

for (int i = 0; i < grvRecord; i++)

{

var chkSel = (CheckBox)grdView.Rows[i].Cells[0].FindControl("chkSel");

if (chkSel.Checked)

{

var employeeDetail = client.Employees.Where(k => k.EmpId == Convert.ToInt32(grdView.Rows[i].Cells[1].Text)).FirstOrDefault();

employeeDetail.EmpName = ((TextBox)(grdView.Rows[i].Cells[2].FindControl("txtEmployeeName"))).Text;

employeeDetail.EmpAge = Convert.ToInt32(((TextBox)(grdView.Rows[i].Cells[3].FindControl("txtEmployeeAge"))).Text);

employeeDetail.EmpSalary = decimal.Parse(((TextBox)(grdView.Rows[i].Cells[4].FindControl("txtEmployeeSalary"))).Text, CultureInfo.InvariantCulture);

employeeDetail.DOB = Convert.ToDateTime(((TextBox)(grdView.Rows[i].Cells[5].FindControl("txtEmployeeDOB"))).Text);

//Save the changes

client.SaveChanges();

}

}

Step 7:Delete Data(DELETE operation)

Let us look at the below code

Uri myUri = new Uri("http://localhost:51637/EmployeeDataService.svc");

var client = new EmployeeDataServiceClient.WCFDataServiceEntities(myUri);

var grvRecord = grdView.Rows.Count;

 

for (int i = 0; i < grvRecord; i++)

{

var chkSel = (CheckBox)grdView.Rows[i].Cells[0].FindControl("chkSel");

if (chkSel.Checked)

{

var employeeDetail = client.Employees.Where(k => k.EmpId == Convert.ToInt32(grdView.Rows[i].Cells[1].Text)).FirstOrDefault();

//Delete the record

client.DeleteObject(employeeDetail);

//Save the changes

client.SaveChanges();

}

}

In this case whichever "Select" checkbox, the user will choose ,only those records will be deleted.Initially we are finding the record by the "EmpId" and then deleting that record and finally saving the changes

Conclusion

WCF Data Service enables clients to use a web application to access data residing on the server.We can create an EDM that resides between the Database and WCF DataService.The WCF DataService was hosted on the server but the processing was done at the client side.We can create a client application to access the service.This article,I believe, has given us substantial amount of knowledge to do so.Hope this will be helpful.Thanks for reading.Zip file is attached.

Page copy protected against web site content infringement by Copyscape

About the Author

Niladri.Biswas
Full Name: Niladri Biswas
Member Level: Platinum
Member Status: Member
Member Since: 10/25/2010 11:04:24 AM
Country: India
Best Regards, Niladri Biswas
http://www.dotnetfunda.com
Technical Lead at HCL Technologies

Login to vote for this post.

Comments or Responses

Posted by: Ck.kislay on: 6/15/2012 | Points: 25
Nice artlcle Niladri!!

Have some query.
1. There is no Binding and Contract detail in WCF Data service, so will you explain how this WCF Data service is working here?
2. It seems that there is no DatContract and Operation contract, Is this all are handled by DataService class??

Thanks,
Chandan

Login to post response

Comment using Facebook(Author doesn't get notification)