WCF DataContractAttribute
This article provides you an expertise over the WCF data contracts. It is defined in System.Runtime.Serilization namespace of class library. Data contracts are considered as Structural contracts because it defines the structure of data for WCF services. It allows you to decide how data should be serialized on wire. Data contracts works in WCF as the XSD works in XML word.
1.Name
Gets or sets name of data contract. By Default the name of data contract is the name of class, enum or struct for which the contract is applied. This property can be very useful when you have current working contracts and to deal with them you need some different contract name.
[DataContract(Name = "Customer")
public class CompanyCustomer
{
// Code
}
2.Namespace
Set the value of target namespace. If the name of data contract is different in client and server the message does not flow successfully. WCF sets default property to the data contract's current file name. This creates issue when client and server has different namespace name. Solution is to set explicitly namespace or set it to "". The default data contract namespace is like
http://schemas.datacontract.org/2004/07/ [YourNamespace]
[DataContract(
Namespace = "http://StudentBlogs.com/Students/Student" )]
public class Student
{
[DataMember]
Public string StudentName
{Get; set}
}
Data members needs to be added as part of DatContract.
For more details on Data member Attribute Click here DataContractSerilizer
WCF Uses DataContractSerilizer as default way to serialize data. DataContractserilizer uses Opt – In mode to serialize which means member of Data Contract must be explicitly as [DataMember()]. This is the opposite behavior of XMLSerializer which uses the opt out mode where the member which does not needs to be serialized needs to be marked as [NonSerialized()]
DataContractSterilizer
[DataContract]
public class Student
{
[DataMember]
public int StudentID
{ Get; Set; }
[DataMember]
public double StudentMarks
{ Get; Set; }
public DateTime DateOfBirth
{ Get; Set; }
}
In this data contract the value of DateOfBirth will not be serialized as part of message serialization. XMLSerializer
[Serializable()]
public class Student
{
public int StudentID
{ Get; Set; }
public double StudentMarks
{ Get; Set; }
[NonSerialized()]
public DateTime DateOfBirth
{ Get; Set; }
}
For this class the value of DateOfBirth will not be serialized where you have to explicitly mark it as non serializable.