如何在MongoDB 2.7中使用MongoDB C#驱动程序更新通用类型 [英] How to update a generic type with MongoDB C# driver in MongoDB 2.7

查看:116
本文介绍了如何在MongoDB 2.7中使用MongoDB C#驱动程序更新通用类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题之后的代码如何用MongoDB C#驱动程序更新泛型类型不再起作用,如何在MongoDB 2.7中执行相同的操作?

Following code from this question How to update a generic type with MongoDB C# driver no longer works, how to do the same in MongoDB 2.7?

void Update(T entity)
{
    collection.Save<T>(entity);
}

推荐答案

当前Save仅在旧版MongoDB C#驱动程序中可用.您可以在驱动JIRA 中找到带有讨论的未解决故障单.

Currently Save is only available in legacy MongoDB C# driver. You can find unresolved ticket with discussion on driver JIRA.

仍然可以在C#中实现类似的功能. 此处:

It's still possible to implement something similar in C#. The behavior is documented here:

如果文档不包含_id字段,则save()方法将调用insert()方法.在操作过程中,mongo shell将创建一个ObjectId并将其分配给_id字段.

If the document does not contain an _id field, then the save() method calls the insert() method. During the operation, the mongo shell will create an ObjectId and assign it to the _id field.

如果文档包含_id字段,则save()方法等效于upsert选项设置为true且查询谓词位于_id字段的更新.

If the document contains an _id field, then the save() method is equivalent to an update with the upsert option set to true and the query predicate on the _id field.

因此,您可以在C#中引入标记器接口来表示_id字段:

So you can introduce marker interface in C# to represent _id field:

public interface IIdentity
{
    ObjectId Id { get; set; }
}

,然后您可以像这样实现Save:

and then you can implement Save like this:

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 } );
}

这篇关于如何在MongoDB 2.7中使用MongoDB C#驱动程序更新通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆