从 MongoDb + C# 中反序列化没有默认构造函数的对象

本文关键字:默认 构造函数 对象 反序列化 MongoDb | 更新日期: 2023-09-27 18:37:06

考虑两个类:

public class Entity
{
    public ObjectId Id { get; set; }
    public E2 e = new E2(ConfigClass.SomeStaticMethod());
}
public class E2
{
    [BsonIgnore]
    public int counter = 5;
    public DateTime last_update { get; set; }
    public E2(int c)
    {
        counter = c;
    }
}

我将像这样存储 Entity 类型的对象,然后从 MongoDb 中检索/从 MongoDb 中检索(假设集合为空):

var collection = database.GetCollection<Entity>("temp");
collection.Save<Entity>(new Entity());
var list = collection.FindAs<Entity>(new QueryDocument());
var ent = list.Single();

无论ConfigClass.SomeStaticMethod()返回什么,counter字段都将为零(整数的默认值)。但是如果我向 E2 类添加一个默认构造函数,那么counter 5.

这意味着MongoDB的C#驱动程序在调用非默认构造函数时遇到了问题(这是完全可以理解的)。我知道BSON库中定义了BsonDefaultValue属性,但它只能接受constant expressions

我正在尝试做的是从配置文件中加载字段的默认值,而对象的其余部分是从 MongoDb 中检索的!?当然,而且要付出最少的努力。

[更新]

我也用相同的结果对此进行了测试:

public class Entity
{
    public ObjectId Id { get; set; }
    public E2 e = new E2();
    public Entity()
    {
        e.counter = ConfigClass.SomeStaticMethod();
    }
}
public class E2
{
    [BsonIgnore]
    public int counter = 5;
    public DateTime last_update { get; set; }
}

运行此代码会导致counter再次为零!

从 MongoDb + C# 中反序列化没有默认构造函数的对象

我设法像这样完成它:

public class Entity
{
    public ObjectId Id { get; set; }
    public E2 e = new E2();
}
public class E2 : ISupportInitialize
{
    [BsonIgnore]
    public int counter = 5;
    public DateTime last_update { get; set; }
    public void BeginInit()
    {
    }
    public void EndInit()
    {
        counter = ConfigClass.SomeStaticMethod();
    }
}

ISupportInitialize接口带有两种BeginInitEndInit方法,在反序列化过程之前和之后调用。它们是设置默认值的最佳位置。