user153923
user153923

Reputation:

In Visual Studio 2010, How do I remove XmlSerializer to use DataContractSerializer?

I created a .NET 4.0 WCF web service and put it up on our internal server.

Now, I am testing this with a simple project that queries the web service.

However, I have found that all of my property names have been appended with the k_BackingField string.

    [System.Runtime.Serialization.DataMemberAttribute(Name="<WoNumber>k__BackingField", IsRequired=true)]
    public string WoNumberk__BackingField {
        get {
            return this.WoNumberk__BackingFieldField;
        }
        set {
            if ((object.ReferenceEquals(this.WoNumberk__BackingFieldField, value) != true)) {
                this.WoNumberk__BackingFieldField = value;
                this.RaisePropertyChanged("WoNumberk__BackingField");
            }
        }
    }

I did a search on this k_BackingField parameter, and found this link to be my best reference:

how to command serializer not to put k__backingfield

Apparently, I have somehow used the XmlSerializer instead of the DataContractSerializer.

What I can't seem to find is how to "undo" the XmlSerialization and enable the DataContractSerializer.

In my project, I have tried searching the entire project for the following XML keywords, but they do not seem to be pulling up:

Does anyone know how to remove XmlSerialization and then re-add my Service Reference using a DataContractSerializer?

Or, does my WCF Service need to be modified so that it exposes the Serializer I want?

Upvotes: 1

Views: 877

Answers (1)

carlosfigueira
carlosfigueira

Reputation: 87308

The problem isn't that you used the XmlSerializer - the issue is that you're using some classes declared with the [Serializable] attribute on your service, and using automatic properties on that class.

The semantic of types decorated with the [Serializable] attribute as used by the serializers is that its fields will be serialized (not its properties). With automatic properties, the compiler will generate the "backing fields", and when you create a proxy (add a service reference) to the service, it will by default attempt to create a data contract equivalent to the contract in the server.

To fix this you have a few choices, by changing the server-side code:

  • Don't use [Serializable], instead using the [DataContract] model (which requires decorating the properties you want serialized with [DataMember]
  • Keep [Serializable], but don't use properties, use fields instead
  • (if applicable) use POCO serialization (public fields / properties will be serialized), no attribute required.

Another alternative is to share the contract between the server and the client (i.e., don't use Add Service Reference, and copy the data / service contracts from the service project to the client one).

Upvotes: 3

Related Questions