WCF DataMember attribute for read-only fields?

Rachel picture Rachel · Sep 29, 2010 · Viewed 9.5k times · Source

I am trying to create a class with a read-only Id field, however I am having problems retaining the value when the object passes through the WCF server.

I cannot set the [DataMember] attribute on the public property since there is no set method, and I would like to keep it that way if possible since I do not want this value changed by external means. I cannot set the [DataMember] attribute on the private field since it throws an error in partial trust environments.

public class MyClass
{
    private int _id;

    public int Id 
    { 
        get { return _id; } 
    }

    private string _otherProperties;

    [DataMember]
    public string OtherProperties
    {
        get { return _otherProperties; } 
        set { _otherProperties = value; }
    }
}

Is there a way to maintain the value of the Id field while going through the WCF server without making my property public?

Answer

FlySwat picture FlySwat · Sep 29, 2010

You can do this:

public int Id
{
     get;
     private set;
}

This will keep the deserializer happy, while not letting people actually set the ID value. You'll have to set it in the constructor, or in the setter of another property.

However, I do agree with Sanders, in that your DTO should be a dumb container.