Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF DataContract with readonly properties

I'm trying to return a complex type from a service method in WCF. I'm using C# and .NET 4. This complex type is meant to be invariant (the same way .net strings are). Furthermore, the service only returns it and never receives it as an argument.

If I try to define only getters on properties I get a run time error. I guess this is because no setters causes serialization to fail. Still, I think this type should be invariant.

Example:

[DataContract]
class A 
{
   [DataMember]
   int ReadOnlyProperty {get; private set;}
}

The service fails to load due to a problem with serialization.

Is there a way to make readonly properties on a WCF DataContract? Perhaps by replacing the serializer? If so, how? If not, what would you suggest for this problem?

Thanks,
Asaf

like image 292
Asaf R Avatar asked Mar 22 '10 18:03

Asaf R


People also ask

Is DataContract mandatory in WCF?

No, the DataContractAttribute is not required - WCF will infer serialization rules.

What is DataContract in WCF?

A data contract is a formal agreement between a service and a client that abstractly describes the data to be exchanged. That is, to communicate, the client and the service do not have to share the same types, only the same data contracts.

What is DataMember in WCF?

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

put [DataMember] on backing field, you won't need a setter.

like image 185
Krzysztof Kozmic Avatar answered Oct 24 '22 09:10

Krzysztof Kozmic


Make your setter public to satisfy the serializer, but just don't do anything on the setter. Not 'purist' but gets it done

public string MyProperty 
{
    get {
        return this._myProperty
    }
    set {}
}
like image 39
Mike Emo Avatar answered Oct 24 '22 11:10

Mike Emo