WCF Data Representation

  1. Data Contracts
  2. The WCF DataContractAttribute and DataMemberAttribute can be applied to .NET Framework types to indicate that instances of the type are to be serialized into XML, and which particular fields or properties of the type are to be serialized.

    The DataContractAttribute signifies that zero or more of a type’s fields or properties are to be serialized. The DataMemberAttribute indicates that a particular field or property is to be serialized.

    The DataContractAttribute can be applied to a class or structure. The DataMemberAttribute can be applied to a public or private field or a property.

    Instances of types that have the DataContractAttribute applied to them are referred to as data contracts in WCF. They are serialized into XML using DataContractSerializer.

    Example:

    [DataContract]
    public class MyCLass
    {
    [DataMember]
    public string MyField;
    [DataMember]

    private string myPrivateField;

    private string myProperty;
    [DataMember]
    public string MyProperty
    {

    get{return myProperty;}

    set {myProperty=value;}

    }}

  3. Controlling Data Generation
    DataContractSerializer, DataContractAttribute and DataMemberAttribute provide very little control over how a type is represented in XML. You can only specify the namespaces and names used to represent the type and its fields or properties in the XML, and the sequence in which the fields and properties appear in the XML.

    [DataContract(
    Namespace="urn:Contoso:2006:January:29",
    Name="LineItem")]
    public class LineItem
    {
    [DataMember(Name="ItemNumber",IsRequired=true,Order=0)]
    public string itemNumber;
    [DataMember(Name="Quantity",IsRequired=false,Order = 1)]
    public decimal quantity;
    [DataMember(Name="Price",IsRequired=false,Order = 2)]
    public decimal unitPrice;
    }
    DataMemberAttribute for use with the DataContractSerializer shows explicitly which fields or properties are serialized. Therefore, data contracts are explicit contracts about the structure of the data that an application is to send and receive.
  4. Versionning
    The DataMemberAttribute has an IsRequired property that can be assigned a value of false for members that are added to new versions of a data contract that were not present in earlier versions, thereby allowing applications with the newer version of the contract to be able to process earlier versions.
    By having a data contract implement the IExtensibleDataObject interface, one can allow the DataContractSerializer to pass members defined in newer versions of a data contract through applications with earlier versions of the contract.