The answer is in this article.
The IgnoreDataMemberAttribute attribute is only honored when used with unmarked types. This includes types that are not marked with one of the DataContractAttribute, SerializableAttribute, CollectionDataContractAttribute, or EnumMemberAttribute attributes, or marked as serializable by any other means (such as IXmlSerializable).
In your case, to omit the UserCode property - just do not mark with any serialization attributes:
[DataContract(Name="Activity")]
public class ActivityDTO
{
[DataMember(Name = "id")]
public int Id { get; set; }
public string UserCode { get; set; }
}
Added: As you want deserialization to behave differently from serialization, I see 2 ways to achieve this:
a) described here: How can I prevent a datamember from being serialized The disadvantage is that it is not thread-safe.
[DataContract( Name = "Activity" )]
public class ActivityDTO
{
private string _userCode;
[DataMember( Name = "id" )]
public int Id { get; set; }
[DataMember( Name = "usercode" , EmitDefaultValue = false )]
public string UserCode { get; set; }
[DataMember( Name = "value" )]
public string Value { get; set; }
[OnSerializing]
private void OnSerializing( StreamingContext context )
{
_userCode = UserCode;
UserCode = default( string );
}
[OnSerialized]
private void OnSerialized( StreamingContext context )
{
UserCode = _userCode;
}
}
b) you can go custom all the way and implement ISerializable:
[Serializable]
public class ActivityDTO : ISerializable
{
public int Id { get; set; }
public string UserCode { get; set; }
public string Value { get; set; }
public ActivityDTO()
{
}
public ActivityDTO( SerializationInfo info , StreamingContext context )
{
Id = info.GetInt32( "id" );
UserCode = info.GetString( "usercode" );
Value = info.GetString( "value" );
}
public void GetObjectData( SerializationInfo info , StreamingContext context )
{
info.AddValue( "id" , Id );
info.AddValue( "value" , Value );
}
}