Set DataContract and DataMember Without All the Attributes

后端 未结 3 931
死守一世寂寞
死守一世寂寞 2021-02-18 18:23

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?

相关标签:
3条回答
  • 2021-02-18 18:56

    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;  
    }
    
    0 讨论(0)
  • 2021-02-18 19:01

    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.

    0 讨论(0)
  • 2021-02-18 19:01

    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.

    0 讨论(0)
提交回复
热议问题