Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

WCF databinding using ADO.NET

1.71/5 (5 votes)
2 Dec 2009CPOL2 min read 41.3K   1.5K  
This basic example illustrates invoking database tables using a WCF service.

Introduction

When I wanted to learn creating WCF Web Services, I thought it would not be a bad idea to do databinding using ADO.NET. Many articles I went through used LINQ to SQL. Although this was helpful, I decided to do a WCF app that retrieves data off of a database using plain ADO.NET. When I looked, there weren't any articles that would demonstrate that. This is a very basic example like a Hello World for retrieving data from a SQL Server database.

Background

As we all know, the DataContract attribute class is used to mark types you write as participating in the WCF serialization via the DataContractSerializer. Marking your classes with this attribute ensures that they can be sent to and from disparate clients in an efficient manner. This is automatically done when we use LINQ classes (.dbml) when you mark the property of the class for "uni-directional serialization".

We will try to retrieve all the records from a table in a database. I used my company database in this example. But you can change it to be the Northwind database by just changing the query.

The project involves creating a "WCF Service application" and a web client to test the service.

Using the code

We define the interface with two operation contracts as below:

C#
//IMyService.cs
[OperationContract]
Shipper GetShipper(int shipperID);

[OperationContract]
Shipper saveShipper(Shipper shipper);

Now let's define the Data Contract with the two data members which need to be serialized.

C#
//Define the data contract IMyService.cs
[DataContract]

public class Shipper
{
    [DataMember]
    public int ShipperID
    {
        get; set;
    }
    [DataMember]
    public DataSet dsTable
    {
       get;set;
    }

Web client

Create a regular ASP.NET website and add a web reference to the Web Service just created, and invoke the methods.

Points of interest

The entire thing took about 30 minutes to do, mainly because I did not know how I should mark serialization for the data. I hope this is useful for folks just starting with WCF services and databinding. I'm happy I learnt databinding, and this would be a good starting point to develop bigger applications. I tried LINQ, but did not succeed with invoking the service asynchronously. I plan to try again. This is my first article here, so any comments / suggestions are welcome.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)