I'm trying to generate KnownType lists for arbitrary objects, and I'm running into problems when trying to serialize types with generic members, such as DbEntityValidationException which has a list property of type IEnumerable<DbEntityValidationResult>.
When calling the constructor for DataContractSerializer, I feed it a list of KnownTypes consisting of the following types, constructed by using reflection to grab the types of all of its properties, as well as any generic type arguments:
var serializer = new DataContractSerializer(source.GetType(), knownsTypesPlusGenerics);
var stringWriter = new StringWriter(CultureInfo.InvariantCulture);
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
serializer.WriteObject(xmlTextWriter, source);
}
This list consists of the following types, captured via tracing:
System.Data.Entity.Validation.DbEntityValidationException
System.Collections.Generic.List`1[[System.Data.Entity.Validation.DbEntityValidationResult, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
System.Collections.ListDictionaryInternal
System.Data.Entity.Validation.DbEntityValidationResult
Yet, for some reason, DataContractSerializer throws on missing types, as if the type of the list property was List<object> instead of List<DbEntityValidationResult>:
System.Runtime.Serialization.SerializationException: Type 'System.Collections.Generic.List``1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' with data contract name 'ArrayOfanyType:http://schemas.microsoft.com/2003/10/Serialization/Arrays' 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.
Why would DataContractSerializer complain about this type when that type isn't used, and when I've provided the type that actually is?
It is possible that somewhere in your object graph, List<{object}> needs to be serialized.
DataContractSerializer sees List<{object}> as being different than List<{any other type}> so typeof(List<{object}>) must be one of the Type's passed on to the DataContractSerializer constructor.
Try that and see if it helps.