如何在MongoDB C#驱动程序中访问嵌套元素

bqucvtff  于 2022-11-28  发布在  Go
关注(0)|答案(1)|浏览(176)

我在我的.Net核心应用程序中实现了一个MongoDB驱动程序。我将按如下方式添加数据模型类,

namespace Test.Database
{
    public class DocumentFields
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }
        [BsonElement("account_id")]
        public string AccountId { get; set; }
        [BsonElement("document_types")]
        public DocumentType[] DocumentTypes { get; set; }
        [BsonElement("document_themes")]
        public DocumentTheme[] DocumentThemes { get; set; }
        [BsonElement("created_at")]
        public DateTime CreatedAt { get; set; }
    }
    public class DocumentType
    {
        [BsonElement("id")]
        public string id { get; set; }
        [BsonElement("name")]
        public string name { get; set; }
    }
    public class DocumentTheme
    {
        [BsonElement("id")]
        public string id { get; set; }
        [BsonElement("name")]
        public string name { get; set; }
    }

}

但是当我尝试使用这个模型类获取数据时,它会出现这个错误。

System.FormatException: An error occurred while deserializing the DocumentThemes property of class Test.Database.DocumentFields: 
Element 'id' does not match any field or property of class Test.Database.DocumentTheme.

我试图访问的文档是这样的。

{
    "_id" : ObjectId("6234410f0f4dd20dd96fb9dd"),
    "account_id" : "96f35500-584e-4db9-94cd-ebd93cce13b7",
    "created_at" : ISODate("2022-03-18T08:21:35.695+0000"),
    "document_themes" : [
        {
            "id" : "6ad3eac9-e44c-4fdd-b54a-f0ff9165ba3e",
            "name" : "Theme 1"
        },
        {
            "id" : "2dd625f2-de57-41f7-9d89-a0e28c62dc65",
            "name" : "Theme 2"
        },
        {
            "id" : "af3347c7-12cc-421a-8945-65ce80bf8a0f",
            "name" : "Theme 3"
        }
    ],
    "document_types" : [
        {
            "id" : "c0934926-9e1d-468c-9a47-97a62d83228d",
            "name" : "Type 1"
        },
        {
            "id" : "331ad071-7d91-4b84-bdf1-733f9868b979",
            "name" : "Type 2"
        },
        {
            "id" : "630bbcad-34ec-4b4d-84e4-89724bd8ae17",
            "name" : "Type 3"
        }
    ]
}

我怎样才能克服这个障碍呢?

6tqwzwtp

6tqwzwtp1#

迟来的回答。
this question类似,.NET/C#驱动程序会将属性id/Id/_id系结至文件中的_id字段。

解决方案1

实作类别Map以覆写id属性的预设行为。

BsonClassMap.RegisterClassMap<DocumentType>(cm =>
{
    cm.AutoMap();
    cm.UnmapField(x => x.id);

    cm.MapMember(x => x.id)
        .SetElementName("id");
});

BsonClassMap.RegisterClassMap<DocumentTheme>(cm =>
{
    cm.AutoMap();
    cm.UnmapField(x => x.id);

    cm.MapMember(x => x.id)
        .SetElementName("id");
});

演示

解决方案2

[BsonNoId]属性套用至DocumentTypeDocumentTheme类别,以隐藏预设的Id行为。

[BsonNoId]
public class DocumentType
{
    ...
}

[BsonNoId]
public class DocumentTheme
{
    ...
}

演示

相关问题