Data Contract Serialization and De-Serialization – WCF Service Tutorial

Serialization is the process of converting an object to transferable data format. By default WCF uses DataContractSerializer. And vice-versa process is called De-Serialization.
   

 public class Product
    {
        public int  ProductID
        {
            get;set;
        }
        public string ProductName
        {
            get;set;
        }
        public string ProductSeller
        {
            get;set;
        }
        public decimal ProductCost
        {
            get;set;
        }
    }
 
Browse the service and open WSDL file.

Notice a namespace containing datacontract
Open the URL highlighted below.

 
 
You may notice the details that I added in Product class.
 
After adding Serializable attribute:
 [Serializable]
    public class Product
    { }
 
Now you may notice the change in xml file. Serializable attribute serialize all private properties.
 
Now if you want a control over serialization. Means you don’t want all data to send to client only few of the  you want to exchange.
Use DataContract and DataMember attribute
[DataContract]
    public class Product
    {
        [DataMember]
        public int  ProductID
        {
            get;set;
        }
        [DataMember]
        public string ProductName
        {
            get;set;
        }
        public string ProductSeller
        {
            get;set;
        }
        public decimal ProductCost
        {
            get;set;
        }
    }
 
In below code, i have added DataMemeber attribute with ProductID and ProductName
Let’s see the WSDL file.
 
You may notice only ProductID and ProductName is showing below why because I have used DataMember attribute with these two.
 

Summary:

  • If we use Serialize attribute then we will not have any control over fields. All fields will be serialize.
  • If we use DataContract attribute then we can control the fields by adding DataMember attribute if we want to serialize else with no attribute.
Please follow and like us:

Leave a Comment