[英]How to update a generic type with MongoDB C# driver in MongoDB 2.7
以下问题中的代码如何使用MongoDB C#驱动程序更新通用类型不再起作用,如何在MongoDB 2.7中执行相同操作?
void Update(T entity)
{
collection.Save<T>(entity);
}
当前Save
仅在旧版MongoDB C#驱动程序中可用。 您可以在JIRA驾驶员的讨论中找到未解决的罚单。
仍然可以在C#中实现类似的功能。 该行为记录在这里 :
如果文档不包含_id字段,则save()方法将调用insert()方法。 在操作期间,mongo shell将创建一个ObjectId并将其分配给_id字段。
和
如果文档包含_id字段,则save()方法等效于upsert选项设置为true且查询谓词位于_id字段的更新。
因此,您可以在C#中引入标记器接口来表示_id
字段:
public interface IIdentity
{
ObjectId Id { get; set; }
}
然后您可以像这样实现Save
:
public void Update<T>(T entity) where T : IIdentity
{
if(entity.Id == ObjectId.Empty)
{
collection.InsertOne(entity); // driver creates _id under the hood
}
else
{
collection.ReplaceOne(x => x.Id == entity.Id, entity, new UpdateOptions() { IsUpsert = true } );
}
}
或更简单:
public void Update<T>(T entity) where T : IIdentity
{
if(entity.Id == ObjectId.Empty)
{
entity.Id = ObjectId.GenerateNewId();
}
collection.ReplaceOne(x => x.Id == entity.Id, entity, new UpdateOptions() { IsUpsert = true } );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.