C#中自定义id字段时的MongoDB反序列化

bom*_*bek 5 c# poco mongodb

我在数据库中有以下结构:

{
      "_id" : ObjectId(""),
      "title" : "something",
      "id" : 1,
      (...)
}
Run Code Online (Sandbox Code Playgroud)

基本上我想从以下集合中检索数据到我的班级:

[BsonIgnoreExtraElements]
public class Topic
{
    [BsonElement("id")]
    public int Id { get; set; }
    [BsonElement("title")]
    public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

问题是这段代码不起作用 -> 执行时显示错误消息: Cannot deserialize a 'Int32' from BsonType 'ObjectId',但这一个可以:

[BsonIgnoreExtraElements]
public class Topic
{
    [BsonIgnore]
    public int Id { get; set; }
    [BsonElement("title")]
    public string Name { get; set; }
    [BsonElement("id")]
    public int IdTest { get; set; }
Run Code Online (Sandbox Code Playgroud)

似乎反序列化拼命地尝试将名称为“Id”的类属性与数据库中的 ObjectId 进行匹配,这是不正确的,因为我明确声明我想将其与 BsonElement("id") 而不是 ("_id") 匹配。

我很欣赏任何如何让它按照我的需要工作的想法。

bom*_*bek 1

我最终这样做了:

public class Topic
{
    public int Id { get; set; }
    public string Name { get; set; }
}

[BsonIgnoreExtraElements]
public class TopicMapper
{
    [BsonElement("title")]
    public string Name { get; set; }
    [BsonElement("id")]
    public int Identity { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

和这个:

var list = await col.Find(new BsonDocument()).ToListAsync().ConfigureAwait(false);
        foreach(var doc in list)
        {
            if(doc.Name != null)
               topics.Add(new Topic{
                Id = doc.Identity,
                Name = doc.Name
               });
        }
Run Code Online (Sandbox Code Playgroud)