C#MongoDB尝试将enum:uint32转换为int32并崩溃

我有一个枚举

public enum MyEnum : uint
    {
        ValueA = 1233104067,
        ValueB= 1119849093,
        ValueC= 2726580491
}

每当我用这个枚举创建一个类并尝试将其存储到数据库中时.
 例如

class MyClass {
    public MyEnum newValue = MyEnum.ValueC;
}

它将使程序崩溃并出现此错误

Unhandled Exception: System.OverflowException: Value was either too large or too small for an Int32.
   at System.Convert.ThrowInt32OverflowException()
   at System.UInt32.System.IConvertible.ToInt32(IFormatProvider provider)
   at MongoDB.Bson.Serialization.Serializers.EnumSerializer`1.Serialize(BsonSerializationContext context, BsonSerializationArgs args, TEnum value)

它尝试将uint值转换为int,但它们太大而且会抛出异常.

我该如何解决这个问题?

谢谢.

最佳答案 MongoDB将数据存储为BSON,即
doesn’t have unsigned integer types.

你有三个选择:

>注释您的未签名类型.

如果使用驱动程序v2.4.3或更早版本:

public class MyClass
{
    [BsonRepresentation(BsonType.Int32, AllowOverflow = true)]
    public MyEnum Value1 = MyEnum.ValueC;

    [BsonRepresentation(BsonType.Int32, AllowOverflow = true)]
    public uint Value2 = uint.MaxValue;
}

不幸的是,驱动程序v2.4.4及更高版本中的序列化程序不尊重
AllowOverflow,无论如何抛出异常(测试和
确认,感谢dnickless指出这一点).这是一个解决方法
(以牺牲一些浪费的空间为代价):

public class MyClass
{
    [BsonRepresentation(BsonType.Int64)]
    public MyEnum Value1 = MyEnum.ValueC;

    [BsonRepresentation(BsonType.Int64)]
    public uint Value2 = uint.MaxValue;
}

>使用签名类型并在适当的时候转换.

// Defaults to int.
public enum MyEnum
{
    ValueA = 1233104067,
    ValueB = 1119849093,
    ValueC = unchecked((int)2726580491)
}

// Usage.
uint a = (uint)MyEnum.ValueA;
uint b = (uint)MyEnum.ValueB;
uint c = unchecked((uint)MyEnum.ValueC);
uint d = (uint)document["MyProperty"].AsInt32; // Reading from a BsonDocument.

>手动序列化(UInt32Serializer,UInt64Serializer等).

点赞