The DataMember attribute has some extra properties that allows us to add some extra rules. For example if a property should always be available, we use (IsRequired=true); to indicate this. These rules are checked when a message is received or send.
[DataContract]
public class TestClass
{
[DataMember(IsRequired = true)]
public string RequiredValue { get; set; }
}
However during our test we noticed that it doesn’t work.
What’s confusing here is that a DataMember has (EmitDefaultValue=true) set by default. An string property’s value starts as String.Empty.
Turn this off by using (EmitDefaultValue=false). Now, a property’s value is null, letting (IsRequired=true) do its validation work as desired.
[DataContract]
public class TestClass
{
[DataMember(IsRequired = true, EmitDefaultValue=false)]
public string RequiredValue { get; set; }
}
Although it’s still not what we expected. If we add a not-required property(e.g. NotRequiredValue) that refers to a class(e.g. ChildClass) that has a required property(e.g. RequiredValue) the validation fails saying that the RequiredValue is missing. Anyone who has a solution?
[DataContract]
public class TestClass
{
[DataMember(IsRequired = true)]
public string RequiredValue { get; set; }
[DataMember(IsRequired = false)]
public ChildClass NotRequiredValue { get;set; }
}
[DataContract]
public class ChildClass
{
[DataMember(IsRequired = true)]
public string RequiredValue { get; set; }
}
0 comments:
Post a Comment