I have found that my WCF services work normally when the data types involved doesn't have the [DataContract]
, but the [Serializable]
instead.
But all the WCF tutorials shows the first one instead of the latter. Why?
[DataContract] attribute specifies the data, which is to serialize (in short conversion of structured data into some format like Binary, XML etc.) and deserialize(opposite of serialization) in order to exchange between the client and the Service.
DataContact. A datacontract is a formal agreement between a client and service that abstractly describes the data to be exchanged. In WCF, the most common way of serialization is to make the type with the datacontract attribute and each member as datamember. Creating a basic DataContract and DataMember.
Windows Communication Foundation (WCF) uses the DataContractSerializer as its default serialization engine to convert data into XML and to convert XML back into data. The DataContractSerializer is designed to serialize data contract types.
A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. Data contract can be explicit or implicit. Simple type such as int, string etc has an implicit data contract.
DataContractAttribute gives you more control over what gets sent over the wire, so you can opt to only send the necessary fields of a given entity. Serializable uses platform serialization, which assumes .NET and the same (or similar) versions of the types on both ends of the wire- it (usually) serializes all the private members, state, etc. DCS is intended for a lightweight XML-ish representation that you can have some control over, and XmlSerializer is for an XML format that you can have very fine control over (attribute data, etc).
It's not enough to mark the class with [DataContract], you have to decorate the fields you want to be serialized with [DataMember] as well.
The Data Contract is an "opt in" model of serialization, where the XML serialzier is "opt out."
One advantage is that the DataContract serializer is much quicker than the old XmlSerializer.
Edit: The examples would show the [DataContract] attribute because it is the one that is designed for the DataContractSerializer that WCF uses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With