MongoDB C#-未调用ISupportInitialize方法

时间:2018-08-30 10:22:32

标签: 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()
            };
        }
    }
}

现在,由于某些原因,即使MongoDB文档指出应automagically发生,也从未调用EndInit方法。

我正在使用以下代码与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方法? 预先感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

我找到了问题。

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

请参见MongoDB Jira上的docs,以及this issue类中的第131至150行。

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