Data Contract Example

As we know that WCF exchange information in XML format. Data contract defines which data type is serialized (convert into Xml). Primitive data types like int, string etc. serialized already as they defined in XSD (Xml Schema Definition). But custom data types like classes are not.

Wcf uses serialization engine i.e. Data Contract Serializer by default to serialize and Deserialize the data.

We can use DataContract attribute to serialize the class and DataMember attribute to Serialize its member.

Example

In following example I simply create a class EmpData and declare two members in it. In service I create a simple method which returns the object of EmpData with some information.

Interface  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;

[ServiceContract]
public interface ITechAltum
{
    [OperationContract]
    EmpData EmpRec();

}

		
		Data Member Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;
using System.Runtime.Serialization;

[DataContract]
public class EmpData
{
   [DataMember]
    public int id;

  [DataMember]
    public string name;

  public int age;

}

		

As you can see here that I didn’t assign data member attribute on age. So this will not serialize and will not be accessed the outside.

I implement this interface in the following class:-

		using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class TechAltum: ITechAltum

{
   
    public EmpData EmpRec()
    {

        EmpData ev = new EmpData();
        ev.id = 101;
        ev.name = "isha";
        ev.age = 25;
        return ev;
   
    }
}

		
		Changes in Sevice.svc
		<%@ ServiceHost Language="C#" Debug="true" Service="TechAltum" CodeBehind="~/App_Code/TechAltum.cs"  %>
		

Copy this url and create new website where we will call this service. And click on the add service reference.

Now implement it in the client side. As we know that our service will return the object of EmpData class. So we also have to create the object of that class.

		using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ServiceReference1.TechAltumClient ta = new ServiceReference1.TechAltumClient();
        ServiceReference1.EmpData ed = new ServiceReference1.EmpData();
        ed = ta.EmpRec();
        Response.Write(ed.id + " " + ed.name);

    }
}

		

As we didn’t serialize the age so we will not able to access it on our client side as shown in the following image of code.

		Data contract in wcf
		
		Figure 1
		

As we can see that it shows only id and name not age.

Email Address

For any query you can mail me at Malhotra.isha3388@gmail.com.