WCF Service default values
.net, c#, visual-studio-2008, wcf
Solution
The only possible (but ugly and therefore not really satisfying) solution I found this far is using the `OnDeserializing` attribute to set the default values at the start of the deserialization an use the setter of a field to determine if the communicated value should realy be set.
[DataContract(Name = "MyClassDTO")]
public class MyClass
{
private string name;
public MyClass()
{
Init();
}
[DataMember]
public string Name
{
get{ return name; }
set
{
if (!String.IsNullOrEmpty(value))
{
name = value;
}
}
}
private void Init()
{
name = "Default Name";
}
[System.Runtime.Serialization.OnDeserializing]
private void OnDeserializing(StreamingContext ctx)
{
Init();
}
}
Problem
I have following data contract class for my WCF Service: ``` [DataContract(Name = "MyClassDTO")] public class MyClass { private string name = "Default Name"; [DataMember] public string Name { get { return name; } set { name = value; } } } ``` When I use Visual Studio's Add Service Reference function to generate a WCF Service Reference the generated DataContract looks something like this: ``` [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name = "MyClassDTO", Namespace = "xxx")] [System.SerializableAttribute()] public partial class MyClassDTO : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.Runtime.Serialization.OptionalFieldAttribute()] private string NameField; [System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this.NameField; } set { if ((object.ReferenceEquals(this.NameField, value) != true)) { this.NameField = value; this.RaisePropertyChanged("Name"); } } } } ``` That means, the default value "Default Name" gets lost and following behavior occurs: ``` MyClassDTO mcdto = new MyClassDTO(); serviceClient.DoSomething(mcdto); [OperationContract] void DoSomething(MyClass mc){ mc.Name //<-- == null but I want it to be "Default Name" } ``` Is there a way configure the data contract that way, that the defined default value "Default Name" doesn't get lost? additional information: I use a service reference without reuse of types in referenced assemblys, e.g. on the client side the class MyClassDTO is generated an is not aware of the server side class MyClass