Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set DataContract and DataMember Without All the Attributes

Tags:

I find the [DataContract] and [DataMember] attributes a bit messy and would rather do this with code in a config method or something. Is this possible?

like image 298
Jeremy Foster Avatar asked Aug 31 '11 23:08

Jeremy Foster


People also ask

What is DataContract and DataMember?

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.

Is DataMember attribute required?

DataMember attribute is not mandatory to add to serialize data. When DataMember attribute is not added, old XMLSerializer serializes the data. Adding a DataMember provides useful properties like order, name, isrequired which cannot be used otherwise.

What does DataMember mean?

Data Member are the fields or properties of your Data Contract class. You must specify [DataMember] attribute on the property or the field of your Data Contract class to identify it as a Data Member. DataContractSerializer will serialize only those members, which are annotated by [DataMemeber] attribute.

What is DataContract attribute?

[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.


2 Answers

You don't have to use these attributes at all. DataContractSerializer will serialize all public properties with getter and setter but in case of serializing entities with navigation properties you will easily end with exception due to "cyclic reference".

To avoid that exception you must either use [DataContract(IsReference = true)] on your entity class with DataMember on every property you want to serilize or IgnoreDataMember on every property you don't want to serialize.

The last and the most complex option is avoiding attributes completely and custom classes implementing IDataContractSurrogate to control serialization outside of the type.

You can also write your completely custom serialization process or use XML serialization or binary serialization with all its requirements.

like image 178
Ladislav Mrnka Avatar answered Sep 21 '22 15:09

Ladislav Mrnka


No, the DataContractSerializer is an opt-in serializer - you have to tell it what you want included.

With other serializers you need to use things like NonSerializedAttribute or XmlIgnoreAttribute to tell the serializer to leave things alone.

like image 24
Andrew Kennan Avatar answered Sep 21 '22 15:09

Andrew Kennan