DataContract and DataMember in WCF


A data contract is an abstract description of a set of fields with a name and data type for each field. The data contract exists outside of any single implementation to allow services on different platforms to interoperate. 

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

We need to include System.Runtime.Serialization reference to the project. This assembly holds the DataContract and DataMember attribute.




Apply the DataContractAttribute attribute to types (classes, structures, or enumerations) that are used in serialization and deserialization operations by the DataContractSerializer. If you send or receive messages by using the infrastructure, you should also apply theDataContractAttribute to any classes that hold and manipulate data sent in messages. 

You must also apply the DataMemberAttribute to any field, property, or event that holds values you want to serialize. By applying theDataContractAttribute, you explicitly enable the DataContractSerializer to serialize and deserialize the data.

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.


DataContract - attribute used to define the class 
DataMember - attribute used to define the properties

namespace WcfServiceLibSample

{
    [DataContract]
   public  class MyService
    {
        [DataMember(Name="EmpID",IsRequired=false)]
       public int EmpID { get; set; }

        [DataMember]
        public string EmpName { get; set; }

        [DataMember]
        public string EmpBranch { get; set; }

        [DataMember]
        public int EmpSal { get; set; }

        [DataMember]
        public int EmpCode { get; set; }

        [DataMember]
        public string EmpDesignation { get; set; }
      
    }

}

0 Responses to “DataContract and DataMember in WCF”

Post a Comment

Labels

Topics