Mongo C#驱动程序:使用带子文档的继承时不返回所有数据

时间:2016-08-25 16:16:18

标签: c# mongodb inheritance mongodb-.net-driver

我正在使用mongodb继承。我可以使用c#驱动程序成功查询每个继承对象的数据,直到我添加一个subDocument。当我查询Document1时,SubDocument1为null,但基础对象具有我期望的ElementA,ElementB和SubDocumentBase的数据。

如果我将BsonIgnoreExtraElements属性从SubDocumentBase类中删除,我会得到一个反序列化错误,因为它正在寻找可能为null的elementC元素,具体取决于我查询的继承对象。我的课程结构方式可能有些不对劲。我们将不胜感激。

        BsonClassMap.RegisterClassMap<Document1>(cm =>
        {
            cm.AutoMap();
            cm.SetDiscriminator("MyDiscriminator");
        });

        var client = new MongoClient("mongodb://localhost:27017");
        var server = client.GetServer();
        var db = server.GetDatabase("myDb");
        var collection = db.GetCollection<BsonDocument>("myCollection");
        var query = collection.AsQueryable<DocumentBase>().OfType<Document1>();

[CollectionName("myCollection")]
public abstract class DocumentBase
{
    [BsonElement("elementA")]
    public DateTime ElementA { get; set; }

    [BsonElement("elementB")]
    public DateTime ElementB { get; set; }

    [BsonElement("subDocument")]
    public SubDocumentBase SubDocumentBase { get; set; }

}
public class Document1 : DocumentBase
{
    public SubDocument1 SubDocument1 { get; set; }
}

public class SubDocument1 : SubDocumentBase
{
    [BsonElement("elementC")]
    public string ElementC { get; set; }
}

[BsonIgnoreExtraElements]
public class SubDocumentBase
{
    [BsonElement("subElementA")]
    public string SubElementA { get; set; }

    [BsonElement("subElementB")]
    public string SubElementB { get; set; }
}

1 个答案:

答案 0 :(得分:0)

我从基类移动了BsonElement。到派生类。

        [CollectionName("myCollection")]
        public abstract class DocumentBase
        {
            [BsonElement("elementA")]
            public DateTime ElementA { get; set; }

            [BsonElement("elementB")]
            public DateTime ElementB { get; set; }

            // I moved this to the SubDocument1 property
            [BsonElement("subDocument")]
            public SubDocumentBase SubDocumentBase { get; set; }

        }
        public class Document1 : DocumentBase
        {
            // I moved BsonElement here
            [BsonElement("subDocument")]
            public SubDocument1 SubDocument1 { get; set; }
        }

        public class SubDocument1 : SubDocumentBase
        {
            [BsonElement("elementC")]
            public string ElementC { get; set; }
        }

        [BsonIgnoreExtraElements]
        public class SubDocumentBase
        {
            [BsonElement("subElementA")]
            public string SubElementA { get; set; }

            [BsonElement("subElementB")]
            public string SubElementB { get; set; }
        }