Question

When using DataContractSerializer to write a DataContract with a member like:

  [DataMember]
  public PropertyId PropId { get; set; }

It reports a serialization error:

SerializationException: Enum value '8493' is invalid for type 'EnumType' and cannot be serialized. Ensure that the necessary enum values are present and are marked with EnumMemberAttribute attribute if the type has DataContractAttribute attribute.

Yes, that particular enum value does not exist within the C# Enum definition because the PropertyId's are dynamic and may be added to the DB (but not deleted) between recompiles.

Since we do not wish to require a recompile of the code just because a property was added, is there any workaround for this type of issue besides typecasting and serializing as an Int32 (that's where we started from but moved to improve type safety/readability).

We would like to use this same concept to extend type safety to even more "generic" ID's. For instance, say something like OrderId. There is an advantage to defining it as an enum to get the type safety throughout C#. The actual enum values will not exist because they have a lifespan corresponding more with runtime vs compile time.

Similar:

9974127/serializing-object-with-invalid-enum-value

8913631/wcf-datacontract-class-with-enum-causes-enum-value-1-is-invalid-for-type-e

Was it helpful?

Solution 3

Still a workaround but it is possible to at least hide the typecasting to Int32 inside the DataContract and not actually serialize the Enum over the wire (no [DataMember]).

    public PropertyId PropId   // Reflect an Int32 backing store to support deserialization of unknown Enum values
    {
        get { return (PropertyId)_propIdValue; } 
        set { _propIdValue = (Int32)value; } 
    }

    [DataMember]
    private Int32 _propIdValue { get; set; }

OTHER TIPS

I also came across the same issue. Make the Enum field nullable with ? mark.

  [DataMember]
  public PropertyId? PropId { get; set; }

I've encountered the same issue as "Dhanuka777". Regardless if you're creating the enum dynamically or not.

Enum values marked with the attribute [EnumMember], will be set as a different value from the source.

For example:

// Source
public enum myEnum
{
    [EnumMember]
    someEnumVal = 99,
}
// --------------------------------------------------------------------- //
// Service Reference code
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
[System.Runtime.Serialization.DataContractAttribute(Name="myEnum")]
public enum myEnum : int {

    [System.Runtime.Serialization.EnumMemberAttribute()]
    someEnumVal  = 0,
}

If you're not explicitly setting your enum values, you're fine. If not, then I would recommend "crokusek" workaround.

BTW, I've encountered this issue with .NET version 4.5.2.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top