【问题标题】:BsonSerializer.Deserialize<T>(bsonDocument) - Id field of child object causes exceptionBsonSerializer.Deserialize<T>(bsonDocument) - 子对象的 Id 字段导致异常
【发布时间】:2017-06-13 18:00:17
【问题描述】:

我有一个 A 类和一个 B 类和 C 类

public class A  
{ 
    public string Id {get;set;}
    public List<B> Children {get;set;}
}
public class B
{
    public string Id {get;set;}
    public string Foo {get;set;}
    public double Bar {get;set;}
}
public class C 
{
    public string Id {get;set;}
    //This property will hold a serialized version of Class A.
    //The scenario requirement is that it can hold any arbitrary BsonDocument of different types
    public BsonDocument Properties {get;set;} 
}

var instanceOfClassC = collection.Find(...).First();

var data = BsonSerializer.Deserialize<A>(instanceOfClassC.Properties);

最后一行导致下面的异常。 如果我将忽略 BsonElement 添加到 B 类的 Id 属性中,它可以正常工作。 但我需要那个 Id 属性!

例外:

MongoDB.Bson.dll 中出现“System.FormatException”类型的未处理异常

附加信息:反序列化 NameSpace.A 类的 Children 属性时出错:元素“Id”与 NameSpace.B 类的任何字段或属性都不匹配。

MongoDB.Bson.dll 中出现“System.FormatException”类型的未处理异常

问题似乎在于属性 B.Id 实际上在 MongoDb 中存储为“Id”,因为它在存储之前已“序列化”为 BsonDocument。否则,相同的模式总是可以完美运行,但 MongoDb 会在写入时转换 Id => _id。

要求:类 C.Properties 包含任意种类的其他有效类类型,并且不能在类声明中更改为类型 A。它工作顺利 - 除了嵌套的 Id 属性!

更新:找到了一个残酷的破解解决方案:在将 BsonDocument 中的所有“Id”属性重命名为“_id”,然后再将其运送到 MongoDb。然后反序列化按预期工作。我用 json 的字符串替换来做到这一点 json.Replace("\"Id\"", "\"_id\"")

谁有更好的解决方案?

【问题讨论】:

    标签: c# mongodb deserialization mongodb-.net-driver bson


    【解决方案1】:

    更清洁的解决方案是:

    public class A  
    { 
        public string Id {get;set;}
        public List<B> Children {get;set;}
    }
    [BsonNoId] // this solves the problem
    public class B
    {
        public string Id {get;set;}
        public string Foo {get;set;}
        public double Bar {get;set;}
    }
    

    你也可以在没有属性的情况下使用 BsonClassMap:

    BsonClassMap.RegisterClassMap<B>(cm =>
    {
        cm.SetIdMember(null);
    });
    

    如果您要映射的类型来自不同的库,这很有用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-02
      • 1970-01-01
      • 2018-11-11
      • 1970-01-01
      相关资源
      最近更新 更多