Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF Serializeable entity and __BackingField

We have a 3rd party dll wich contains (among other things) our entities.
The entites are all marked with the [Serializeable] attribute.

We now need to creat a new WCF services which will expose some of this entities.
The problem is, since the entites are not declared with the DataContract and DataMember attributes, the property names are appended with __BackingField!

I know using the DataContarct\Member attributes will solve this issue, but given that I cannot modify the 3rd party dll with the entities, is there a different workaround?

like image 933
sternr Avatar asked Sep 04 '11 15:09

sternr


2 Answers

Types decorated with the [Serializable] attribute have their fields serialized, not properties (that's the [Serializable] "contract"). If the 3rd party types use automatic properties (as shown below), the compiler will create a field with the k_BackingField suffix, and this is what will be serialized.

If you cannot change the types in the 3rd party library, one alternative would be to use that same library on the client. When creating the proxy for the service (using either svcutil or Add Service Reference), you can reference the 3rd party library, and the generated client won't create new types for the contracts, instead reusing the types from the library. This way you won't have to deal with types with public _BackingField property names.

Automatic properties:

[Serializable]
public class MyType
{
    public string MyProp { get; set; }
}

The compiler will turn it into something similar to

[Serializable]
public class MyType
{
    private string <MyProp>k_BackingField;
    public string MyProp
    {
        [CompilerGenerated]
        get { return this.<MyProp>k_BackingField; }
        [CompilerGenerated]
        set { this.<MyProp>k_BackingField = value; }
    }
}
like image 80
carlosfigueira Avatar answered Nov 18 '22 10:11

carlosfigueira


You can use the XmlSerializerFormatAttribute to use XmlSerializer instead of DataContractSerializer in the service implementation.

It will perform slower but it should sovle your problem.

like image 1
Huusom Avatar answered Nov 18 '22 09:11

Huusom