CRUD operation fails with Bson Serialization Exception

I am getting

MongoDB.Bson.BsonSerializationException : GuidSerializer cannot serialize a Guid when GuidRepresentation is Unspecified.

I added the required attribute to the field:
[BsonGuidRepresentation(GuidRepresentation.Standard)]

After doing this, read and write operations work. The delete operation keeps failing with the same error above.

_collection.DeleteOne(filter);

I tried registering GuidSerializer from code but it gives an error that GuidSerializer is already registered (I tried the try… version too )

I am using C# driver 3.1 , .NET 9.0

Thanks

Hi @Ali_Afsari ,

Welcome to the MongoDB Community Forums! Seems like the scenario you’re explaining should work as expected. I tried this with the attribute [BsonGuidRepresentation(GuidRepresentation.Standard)] and CRUD operations seem to work. Do you have a small self contained project where this issue is reproducible?

Thanks,

Rishit.

Hi @Rishit_Bhatia ,

Sure, I created and uploaded the project to this repo:

Thanks,
Ali

Hey @Ali_Afsari That’s quite a comprehensive example which makes it harder to pinpoint where the issue may be. Here’s a simple example (similar to your model class) that has inserts, reads and deletes working with one of the parameters using Guid. I would recommend tracing back from the simple example to root cause the issue, at a quick glance it might be something with the way your constructor is setup which is detecting the GuidRepresentation as Unspecfied. If the error still persists or you think its something indeed with the driver that needs addressing then please feel free to file a CSHARP ticket. Hope that helps.

public class Program
{
    public static async Task Main(string[] args)
    {
        var client = new MongoClient("<Connection_URI>");
        var sampleDatabase = client.GetDatabase("<DB_Name>");
        var sampleCollection = sampleDatabase.GetCollection<Pizza>("<Collection_Name>");

        Pizza veggiePizza = new Pizza
        {
            pizzaId = Guid.NewGuid(),
            type = "Veggie",
            size = "L",
            price = 10.99
        };

        await sampleCollection.InsertOneAsync(veggiePizza);
        Console.WriteLine("Inserted Pizza");

        var restoCheck = await sampleCollection.Find(p=>p.size == "L").FirstOrDefaultAsync();
        Console.WriteLine(restoCheck.ToBsonDocument().ToString());

        //Delete the Pizza
        FilterDefinition<Pizza> deleteFilter = Builders<Pizza>.Filter.Eq("pizzaId", veggiePizza.pizzaId );
        var res = await sampleCollection.DeleteOneAsync(deleteFilter);
        Console.WriteLine($"Deleted: {res.DeletedCount}");

    }
}

public class Pizza
{
    public ObjectId Id { get; set; }    

    [BsonGuidRepresentation(GuidRepresentation.Standard)]
    public Guid pizzaId { get; set; } = Guid.Empty;

    public string type { get; set; }

    public string size { get; set; }

    public double price { get; set; }
}

Thanks,

Rishit.