C# MongoDB Upsert - 'BsonValue(Guid) 已过时:'改用 BsonBinaryData 构造函数并指定 Guid 表示'

问题描述

我是 MongoDB 的新手,正在尝试创建一个 Upsert:

public void UpsertRecord<T>(string collectionName,Guid id,T record)
    {
        var collection = db.GetCollection<T>(collectionName);

        var result = collection.ReplaceOne(
            new BsonDocument("_id",id),record,new ReplaceOptions { IsUpsert = true });
    }

但我在 Visual Studio 中收到以下警告:

'BsonValue.implicit operator BsonValue(Guid) 已过时:使用 BsonBinaryData 构造函数代替并指定 Guid 表示'

任何帮助将不胜感激!

解决方法

我能够通过这种方式修复它:

public void UpsertRecord<T>(string table,Guid id,T record)
    {
        BsonBinaryData binData = new BsonBinaryData(id,GuidRepresentation.Standard);
        var collection = db.GetCollection<T>(table);

        var result = collection.ReplaceOne(
            new BsonDocument("_id",binData),record,new ReplaceOptions { IsUpsert = true });
    }