如何保存/传递MongoDB UpdateDefinition以供日志记录和以后使用



我对如何保存/传递MongoDB UpdateDefinition以进行日志记录以及以后使用感到困惑

我已经为Azure中的MongoDB创建了通用函数,用于获取、插入、删除和更新集合,效果良好。

目的是能够以标准的、预先配置的方式与集合进行交互。特别是对于更新,目标是能够灵活地传入适当的UpdateDefinition,其中业务逻辑在其他地方完成并传入

我可以创建/更新/设置/组合UpdateDefinition本身,但当我试图通过序列化它来记录它时,它显示null:

JsonConvert.SerializeObject(updateDef)

当我尝试记录它,将它保存到另一个类或将它传递给另一个函数时,它显示为null:

public class Account
{
[BsonElement("AccountId")]
public int    AccountId     { get; set; }
[BsonElement("Email")]
public string Email         { get; set; }
}
var updateBuilder = Builders<Account>.Update;
var updates = new List<UpdateDefinition<Account>>();
//just using one update here for brevity - purpose is there could be 1:many depending on fields updated
updates.Add(updateBuilder.Set(a => a.Email, email));
//Once all the logic and field update determinations are made
var updateDef = updateBuilder.Combine(updates);
//The updateDef does not serialize to string, it displays null when logging.
_logger.LogInformation("{0} - Update Definition: {1}", actionName, JsonConvert.SerializeObject(updateDef));
//Class Created for passing the Account Update Information for Use by update function
public class AccountUpdateInfo
{
[BsonElement("AccountId")]
public int                          AccountId   { get; set; }
[BsonElement("Update")]
public UpdateDefinition<Account>    UpdateDef   { get; set; }
}
var acct = new AccountUpdateInfo();
acctInfo.UpdateDef = updateDef
//This also logs a null value for the Update Definition field when the class is serialized.
_logger.LogInformation("{0} - AccountUpdateInfo: {1}", actionName, JsonConvert.SerializeObject(acct));

对正在发生的事情有什么想法或想法吗?我很困惑为什么我不能像那样序列化日志或在类中传递值

尝试一下:

var json = updateDef.Render(
BsonSerializer.SerializerRegistry.GetSerializer<Account>(),
BsonSerializer.SerializerRegistry)
.AsBsonDocument
.ToString();

要将json字符串转换回更新定义(使用隐式运算符(,可以执行以下操作:

UpdateDefinition<Account> updateDef = json;

这是我的想法,没有经过测试。我唯一不确定(没有IDE(的是上面的.Document.ToString()部分。

最新更新