Serialization error when property is declared as base class, but populated by derived class


 
I’ve receive  quite generic error Message :
 Type ‘MyclassType’ with data contract name ‘MyclassType:http://schemas.datacontract.org/myNamespace’ is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types – for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.
Type : System.Runtime.Serialization.SerializationException, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089


After investigation I found that the class that I tried to serialize, had a property declared of the base class, but at runtime derived class was assigned, and serialization was unable to resolve it.
The fix was simple- to add KnownType property to container class.

    [KnownType(typeof(MyclassType))]
public class Mycontainer 
{
 MyBaseclass PropertyOfmyClass { get; set;}
…….
}

public class  MyclassType : MyBaseclass
{ ….}

Unfortunately, the serialization time error message didn’t specify the name of container class , not the name of property. it makes harder to fix the error.

Advertisements