Jerry Nixon @Work: WCF DataMember IsRequired Attribute not working

Jerry Nixon on Windows

Thursday, March 11, 2010

WCF DataMember IsRequired Attribute not working

If you have a DataContract with DataMembers, you can set much of your core validation logic inside the contract itself.

For example, if a model ALWAYS requires a property, you use (IsRequired=true); to indicate it. The rule is validated at serialization.

The problem is it doesn’t work. Or does it?

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.

image

Now you know.