Search code examples
c#mongodbguidupsertobsolete

C# MongoDB Upsert - 'BsonValue(Guid) is obsolete: 'Use the BsonBinaryData constructor instead and specify a Guid representation'


I'm new to MongoDB and am trying to create an 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 });
    }

But I get the following warning in Visual Studio:

'BsonValue.implicit operator BsonValue(Guid) is obsolete: Use the BsonBinaryData constructor instead and specify a Guid representation'

Any help would be much appreciated!


Solution

  • I was able to fix it this way:

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