c# - MongoDB C# - 不调用 ISupportInitialize 方法

标签 c# mongodb

我正在使用 MongoDB C# 驱动程序与 Mongo Atlas 实例通信。 我正在重构一些文档的架构,我想使用 ISupportInitilize 来读取一些额外的元素并将它们转换为新的预期架构。

这是旧文档定义:

public class ImageDocument : DocumentBase, ISupportInitialize
{
    [BsonExtraElements]
    public Dictionary<string, object> ExtraElements;

    //Other elements omitted for brevity.

    public string AzureImageId { get; set; }
    public string AzureImageUrl { get; set; }

    public void BeginInit()
    {
    }

    public void EndInit()
    {
    }
}

这是新的文档定义:

public class ImageDocument : DocumentBase, ISupportInitialize
{
    [BsonExtraElements]
    public Dictionary<string, object> ExtraElements;

    //Other elements omitted for brevity

    public AzureImageInformationPage Original { get; set; } //Original, as uploaded

    public void BeginInit()
    {
    }

    public void EndInit()
    {
        if (Original == null)
        {
            Original = new AzureImageInformationPage {
                AzureImageId = ExtraElements.GetValueOrDefault("AzureImageId").ToString(),
                ImageUrl = ExtraElements.GetValueOrDefault("ImageUrl").ToString()
            };
        }
    }
}

现在,出于某种原因 EndInit 方法从未被调用,即使 MongoDB 文档声明它应该发生 automagically .

我正在使用以下代码与 MongoDB C# 驱动程序交互:

public async Task<IList<T>> RetrieveAll<T>() where T : DocumentBase
{
    return await GetCollection<T>().AsQueryable().ToListAsync();
}

public async Task<IList<T>> RetrieveWhere<T>(Expression<Func<T, bool>> query) where T : DocumentBase
{
    return await GetCollection<T>().AsQueryable().Where(query).ToListAsync();
}

public async Task<T> RetrieveSingle<T>(Expression<Func<T, bool>> query) where T : DocumentBase
{
    return await GetCollection<T>().AsQueryable().SingleOrDefaultAsync(query);
}    

private IMongoCollection<T> GetCollection<T>() where T : DocumentBase
{
    //Slightly modified from the real code, so it's easy to read.
    var collectionName = typeof(T).Name.Replace("Document", string.Empty);

    //Database name is hardcoded for now.
    var database = mongoClient.GetDatabase("MyDb");

    return database.GetCollection<T>(collectionName);
}

如何让 MongoDB 驱动程序调用 ISupportInitialize 方法? 在此先感谢您帮助我。

最佳答案

我发现了问题。

截至撰写本文时,仅在针对 .NET 4.5 进行编译时才支持初始化。 我正在使用 .NET 核心 2.0。

参见 this issue在 MongoDB Jira 上,以及 BsonClassMapSerializer 中的第 131 到 150 行类。

希望 MongoDB 团队尽快在 .NET Core 中添加对序列化的支持。

关于c# - MongoDB C# - 不调用 ISupportInitialize 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52094673/

相关文章:

javascript - 使用Jquery检索YouTube标签

mongodb - 是否可以单独使用对象 id 在 mongodb 中找到文档(不知道哪个集合)?

node.js - Mongoose 文本搜索 - 将其行为更改为 AND 操作会减慢速度

c# - 虚方法和抽象方法的区别

javascript - Mongod 无法正常运行

node.js - 如何发送批量 MongoDB count() 查询?

java - 在集群运行时更新更改

c# - 在 PictureBox() 中绘制矩形或箭头

c# - 在 C# 中,如何使用十六进制值创建 System.Drawing.Color 对象?

c# - 如何使用 HttpRequestMessage 发送证书?