首页 > 解决方案 > MongoDb c# 使用 bsonextraelements 映射递归对象

问题描述

我有以下课程:

public class Property
{ 
    public string Description { get; set; }
    public object Value { get; set; }

    [BsonExtraElements]
    public IDictionary<string, Property> OtherData { get; set; }
} 

public class Device
{
   public string DeviceId { get; set; }
   public IDictionary<string, Property> Properties { get; set; }
}

我想在 json 中实现并映射到这些类是:

{  
   "DeviceId":"asd",
   "Properties":{  
      "PropertyA":{  
         "Description":"some info",
         "PropertyAB":{  
            "Description":"some info",
            "Value":"etc"
         }
      },
      "PropertyB":{  
         "Description":"some info",
         "Value":"etc"
      }
   }
}

因此,如您所见,我想使用 ExtraElements 以递归方式映射具体模型“属性”。但是上面的代码会失败,因为 BsonExtraElements 只能用于 IDicionary 接口。还:

public class Property : IDictionary<string, Property>
{ 
    public string Description { get; set; }
    public object Value { get; set; }
}

不起作用。老实说,这种语义是最需要的。(无需达到额外的属性 OtherData)但是这两种语义我都无法正确映射。有没有人尝试过类似的东西?任何提示如何实现这一目标?

标签: c#mongodbmongodb-.net-driver

解决方案


推荐阅读