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?
-
4what's messy about an upfront decoration?– Mitch WheatAug 31, 2011 at 23:50
-
2Not sure how to answer. Just messy.– Jeremy FosterSep 1, 2011 at 15:26
-
3I have a lot of entities and for the most part I want to extend them all including all properties, so it just feels cumbersome to repeat an attribute hundreds of times. I'm hoping to figure out the "opt out" approach that Ladislov is helping me with below. I'd rather decorate the members I don't want to include.– Jeremy FosterSep 1, 2011 at 15:28
3 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.
-
4But I add [DataContract] to my class and I can return it from a WCF operation... but the contents are blank, so I add [DataMember] to a couple of properties and suddenly those one (and only those ones) are returned in the serialized result. So why isn't mine working as you say where by default all properties are returned? Sep 1, 2011 at 14:34
-
-
8Once you add
DataContract
attribute you must mark properties you want to serialize withDataMember
attribute. Default serialization I described works only if you don't useDataContract
attribute at all. Sep 1, 2011 at 14:47 -
1Works! Yeehaw. Now I need to figure out the lazy loading stuff through WCF, but I'll deal with it and start a new thread if I can't figure it out. Thanks. Sep 1, 2011 at 15:31
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.
I know this is a rather old post, but I came here thinking the same thing if there is a way to set all member attributes automatically on some legacy code with public fields and no getters and setters.
What makes it look just a little bit less messy is shortening up the name DataMember:
using DM = System.Runtime.Serialization.DataMemberAttribute;
[DataContract]
public class SomeClass
{
[DM] public bool IsMO;
[DM] public string LabCode;
[DM] public string OrderNumber;
}