Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
823 views
in Technique[技术] by (71.8m points)

wcf - Why is using [DataMember(EmitDefaultValue = false)] not recommended?

In WCF you can define a contract using the [DataContract] and [DataMember] attributes, like this:

[DataContract]
public class Sample 
{
    [DataMember(EmitDefaultValue = false, IsRequired = false)]
    public string Test { get; set; }
}

This article on the MSDN states that using EmitDefaultValue = false is not recommended:

snippet

However, i like to use this, because the XML that is generated using this construction is cleaner. Not specifying this setting results in:

<Sample>
    <Test xsi:nil="true"/>
</Sample>

while using the setting the element is ommited when there is no value:

<Sample>
</Sample>

I'm curious to what the reasoning behind that statement is. Specifically since both snipptes of XML look equivalent to me (and both last part can be deserialized correctly for this contract).

What is the reasoning behind this statement?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The reason is at the bottom of the article that you link to. The short version is:

  • When the EmitDefaultValue is set to false, it is represented in the schema as an annotation specific to Windows Communication Foundation (WCF). There is no interoperable way to represent this information. In particular, the "default" attribute in the schema is not used for this purpose, the minOccurs attribute is affected only by the IsRequired setting, and the nillable attribute is affected only by the type of the data member.

  • The actual default value to use is not present in the schema. It is up to the receiving endpoint to appropriately interpret a missing element.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...