枚举值“'对于类型>无效'EnumType',不能序列化 [英] Enum value '' is invalid for type > 'EnumType' and cannot be serialized

查看:1396
本文介绍了枚举值“'对于类型>无效'EnumType',不能序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用DataContractSerializer使用如下成员编写DataContract时:

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

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

它报告了序列化错误:


SerializationException:枚举值'8493'对于类型
'EnumType'无效,无法序列化。确保必需的枚举
值存在,并且如果该类型具有DataContractAttribute属性,则标记为EnumMemberAttribute属性

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.

是的,C#枚举定义中不存在特定的枚举值,因为PropertyId是动态的,可能会在重新编译之间添加到DB(但不​​被删除)。

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.

由于我们不想仅仅因为添加了一个属性而需要重新编译代码,除了类型转换和序列化作为Int32之外,是否有任何解决方法(这就是我们开始的地方,但是改进了类型安全/可读性)。

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).

我们希望使用同样的概念将类型安全扩展到更多的通用ID 。例如,说一些类似OrderId的东西。将它定义为枚举以获得C#中的类型安全性有一个优点。实际的枚举值不会存在,因为它们的运行时间与编译时间相对应的寿命更长。

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.

类似:

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

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

推荐答案

我也遇到了同样的问题。使枚举字段为空可以使用?标记。

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

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

这篇关于枚举值“'对于类型>无效'EnumType',不能序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆