views:

472

answers:

4

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?

Thanks!

+1  A: 

Hi Andrey.

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: http://stackoverflow.com/questions/172681/wcf-datacontracts

Russell
So the only way for me to overcome the problem is to make it a method instead of property? Again, I can't allow "set" on this property
Andrey
You could make it a method (eg GetMessage() { return ""; }) alternatively, I am pretty sure you could tell the WCF Serializer to ignore it. I'll see what I can find and let you know.,
Russell
This stackoverflow question hits the nail on the head: http://stackoverflow.com/questions/172681/wcf-datacontracts
Russell
+3  A: 

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

rh
Actually, it works best in my case! Thanks!
Andrey
That is a neat solution!
Russell
Thanks, glad it was useful! This actually is just one of several uses for this trick. Since getters and setters are technically functions, you can also use this same technique to provide custom serialization of primitive types (perhaps a custom time format in XML) without needing to wield the intimidating IDataContractSurrogate.
rh
A: 

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??

marc_s
+2  A: 

Properties with DataMember attribute always requires set. You should re write simmilar object on the client application since DataContract members can always be assigned values.

Jojo Sardez