Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enum value '' is invalid for type > 'EnumType' and cannot be serialized

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

like image 723
crokusek Avatar asked Jun 07 '26 17:06

crokusek


2 Answers

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

  [DataMember]
  public PropertyId? PropId { get; set; }
like image 88
Dhanuka777 Avatar answered Jun 10 '26 09:06

Dhanuka777


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.

like image 36
OZ_CM Avatar answered Jun 10 '26 08:06

OZ_CM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!