Search code examples
silverlightwcf-ria-servicesxmlserializer

XmlSerializer stopped working after updates


I'm using XmlSerializer. I've had no problems with it until now. I updated Silverlight from 4 to 5 and at the same time also updated the WCF RIA Services from v1 SP1 to v1 SP2. Now the following line gives me an error.

XmlSerializer s = new XmlSerializer(typeof(MyCustomObject));

The error is:

System.InvalidOperationException: System.ServiceModel.DomainServices.Client.EntityConflict cannot be serialized because it does not have a parameterless constructor.

The object I'm using (MyCustomObject in the sample) has not changed in any way so I'm starting to think it's either SL5 or the new RIA Services that is breaking my code. I didn't find any breaking changes document or mentions that this could happen. I don't know why it has a problem with EntityConflict since I'm not using any entities within my object.

Has anyone seen an error like this and/or know how to solve it?

UPDATE!

The final property that the error message says before EntityConflict is an Entity. I think that makes a difference but it has been working before. I'd also like to know why the serializer already tries to serialize the object in the constructor?


Solution

  • public static XmlSerializer GetEntityXmlSerializer<TEntity>()
             where TEntity : Entity
    { 
        XmlAttributes ignoreAttribute = new XmlAttributes()
                                        {
                                             XmlIgnore = true,
                                        };
    
        // use base class of Entity, 
        // if you use type of implementation 
        // you will get the error.
        Type entityType = typeof(Entity);
    
        var xmlAttributeOverrides = new XmlAttributeOverrides();
        xmlAttributeOverrides.Add(entityType, "EntityConflict", ignoreAttribute);
        xmlAttributeOverrides.Add(entityType, "EntityState", ignoreAttribute);
    
        return new XmlSerializer(typeof(TEntity), xmlAttributeOverrides);
    }