A data contract is a formal agreement between a service and a client that
abstractly describes the data to be exchanged.

Data contract can be explicit or implicit. Simple type such as int, string etc has an implicit data contract. User defined object are explicit or Complex type, for which you have to define a Data contract using [DataContract] and [DataMember] attribute.

WCF uses a serialization engine called the Data Contract Serializer by default to serialize and deserialize data.We can also explicitly create a data contract by using DataContractAttribute and DataMemberAttribute attributes. This attribute can be applied to classes, structures, and enumerations.

The DataMemberAttribute attribute must then be applied to each member of the data contract type to indicate that it is a data member, that is, it should be serialized.

Data Contracts can be defined as follows:

â€¢ It describes the external format of data ed to and from service operations â€¢ It defines the structure and types of data exchanged in service messagesâ€¢ It maps a CLR type to an XML Schema â€¢ It defines how data types are serialized and deserialized. Through serialization, you convert an object into a sequence of bytes that can be transmitted over a network. Through deserialization, you reassemble an object from a sequence of bytes that you receive from a calling application.â€¢ It is a versioning system that allows you to manage changes to structured data .

Namespace for holding DataContract and DataMember attributes.

System.Runtime.Serialization

Example :

Create User defined data type called Customer. This data type should be identified for serialization and deserialization by mentioning with [DataContract] and [DataMember] attribute.

Add Wcf Service at DataContractinWCF.Web(Silverlight Web Project),We get IService1.cs and Service1.svc files.

In GetCustomerData method we have created the Customer instance and return to the client.As we have created the data contract for the Employee class, client will aware of this instance whenever he creates proxy for the service.

Service1.svc.cs :

namespace DataContractinWCF.Web

{

publicclassService1 : IService1

{

public Cusomer GetCustomerData (int empId)

{

Cusomer CusDetail = new Cusomer ();

//Do something to get Customer details and assign to CusDetail properties

return CusDetail;

}

}

Client Side

On client side we can create the proxy for the service and make use of it. The client side code is shown below.

Build Web project and then Add Service reference to client side.Now we can access the service methods at client side.

On button click event access the service as follows :

Public void btnGetDetails_Click(object sender, EventArgs e)

{

ServiceReference1.Service1Client service = new ServiceReference1.Service1Client();