WCF chokes on properties with no "set ". Any workaround?

I have some class that I'm passing as a result of a service method, and that class has a get-only property:

[DataContract]
public class ErrorBase
{
  [DataMember]
  public virtual string Message { get { return ""; } }
}

I'm getting an exception on service side:

System.Runtime.Serialization.InvalidDataContractException: No set method for property 'Message' in type 'MyNamespace.ErrorBase'.

I have to have this property as only getter, I can't allow users to assign it a value. Any workaround I could use? Or am I missing some additional attribute?


Solution 1:

Give Message a public getter but protected setter, so that only subclasses (and the DataContractSerializer, because it cheats :) may modify the value.

Solution 2:

Even if you dont need to update the value, the setter is used by the WCFSerializer to deserialize the object (and re-set the value).

This SO is what you are after: WCF DataContracts

Solution 3:

[DataMember(Name = "PropertyName")]
public string PropertyName
{
    get
    {
        return "";
    }
    private set
    { }
}

Solution 4:

Couldn't you just have a "do-nothing" setter??

[DataContract]
public class ErrorBase
{
  [DataMember]
  public virtual string Message 
  {
      get { return ""; } 
      set { }
  }
}

Or does the DataContract serializer barf at that, too??

Solution 5:

If you only have a getter, why do you need to serialize the property at all. It seems like you could remove the DataMember attribute for the read-only property, and the serializer would just ignore the property.