我正在使用 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/