c# - 如何保存/传递 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()
上面的部分。
推荐阅读
- python - 将多页pdf连接成单页pdf
- java - 如何使用 MVC 设计模式观察嵌套对象
- java - Hibernate ManyToMany realation
- android - How can I orderByChild on Android Firebase chat based application?
- python-3.x - 计算numpy数组中两点之间的规范距离
- c++ - 如何在 CMake 中“覆盖”文件的扩展类型
- java - How can i remove an element from array in Java
- go - 无法构建具有外部模块本地副本的项目
- regex - How to grep only the desired position match in a single line, where there is multiple matches, using regex?
- log4j - Is there a log4j appender for Moogsoft?