二进制不是 ObjectIdSerializer 的有效表示

Binary is not a valid representation for an ObjectIdSerializer

我正在尝试从我的 TestObject class 设置 ObjectId。唯一的问题是我不断收到异常,我无法调试这个序列化过程。

我的MongoDB:

{
    "_id" : LUUID("964c87a0-bf8a-1f4e-be85-7aadb5315adb")
}

An error has occurred while resolving 'MongoDataSource' data source: An error occurred while invaking data retrieval method.

--- InnerException ---

An error occurred while deserializing the Object property of class TestObject: Cannot deserialize a 'ObjectId' from BsonType 'Binary'.

--- InnerException ---

Cannot deserialize a 'ObjectId' from BsonType 'Binary'.

[DataObject]
public class TestObject
{
    [BsonId]
    [BsonElement("_id")]
    public ObjectId ObjectId { get; set; }
}

如果我把它变成 BsonType.Binary

An error has occurred while resolving 'MongoDataSource' data source: An error occurred while invaking data retrieval method.

--- InnerException ---

Exception has been thrown by the target of an invocation.

--- InnerException ---

Binary is not a valid representation for an ObjectIdSerializer.

[DataObject]
public class TestObject
{
    [BsonId]
    [BsonElement("_id")]
    [BsonRepresentation(BsonType.Binary)]
    public ObjectId ObjectId { get; set; }
}

问题是 Mongo 集合中的字段存储为 LUUID(它是一个 GUID),与 ObjectId 相比是完全不同的类型。

在您的映射 class 中,您定义了

[DataObject]
public class TestObject
{
    [BsonId]
    [BsonElement("_id")]
    public ObjectId ObjectId { get; set; }
}

并且当驱动程序尝试反序列化值 964c87a0-bf8a-1f4e-be85-7aadb5315adb(GUID 的字符串表示)失败时。

好消息,GUID 的 ID 生成器随驱动程序一起提供,您只需遵循驱动程序的约定即可轻松获得所需的结果:

public class TestObject
{
    public Guid Id { get; set; } // note the property is renamed in Id
}

根据 official documentation,您可以省略 [BsonId] [BsonElement("_id")][BsonId(IdGenerator = typeof(GuidGenerator))] 属性,只要 属性 被命名为 Id 及其类型是受支持的类型之一。