Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have optional DataMembers in WCF?

Tags:

wcf

If I have the following class:

[DataContract]
public class GetColorsRS
{
    [DataMember(Name = "Colors", Order = 0, IsRequired=true)]
    public List<Color> Colors { get; set; }

    [DataMember(Name = "Errors", Order = 1, IsRequired=false)]
    public List<Error> Errors { get; set; }
}

If no errors are found in the request, I want to send back a response that does not have an Errors node, however, it passes back an Errors node that is empty. I thought this is what the IsRequired was for?

Just noticed EmitDefaultValue, is this what I am looking for?

like image 441
Xaisoft Avatar asked Jun 06 '11 20:06

Xaisoft


People also ask

What is EmitDefaultValue in WCF?

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.

What is DataMember in WCF?

Data Member are the fields or properties of your Data Contract class. You must specify [DataMember] attribute on the property or the field of your Data Contract class to identify it as a Data Member. DataContractSerializer will serialize only those members, which are annotated by [DataMemeber] attribute.

What is Datacontract and DataMember?

A datacontract is a formal agreement between a client and service that abstractly describes the data to be exchanged. In WCF, the most common way of serialization is to make the type with the datacontract attribute and each member as datamember.

Is Datacontract mandatory in WCF?

No, the DataContractAttribute is not required - WCF will infer serialization rules.


1 Answers

I have determined that EmitDefaultValue should be set to false if I don't want to serialize the default value of the DataMember.

 [DataMember(Name = "Errors", Order = 1, IsRequired=false,EmitDefaultValue=false)]
 public List<Error> Errors { get; set; }
like image 161
Xaisoft Avatar answered Sep 27 '22 18:09

Xaisoft