Search code examples
c#mongodbmongodb-.net-driver

MongoDb id generator is not working


I have a simple need generate string ID if field is null before inserting. It works fine if property has name Id, but otherwise it doesn't.

I have following class:

public abstract class CampaignBase
{
   [BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
   [BsonRepresentation(BsonType.ObjectId)]
   public string CampaignId { get; set; }
}

public class Campaign : CampaignBase {}

Now when I insert MyData in the database I get null instead of generated id. It seems that these attributes just are not applied, because if property has Id name then if works fine and attribute can change actual data layout (string/objectid/etc).

This is how I save it:

enter image description here

campaign and campaignBase are referencing to the same object, so don't mind it.

Where UpdateOptions:

protected static UpdateOptions UpdateOptions => new UpdateOptions
{
    IsUpsert = true
};

And here it is: null is arriving:

enter image description here

Am I missing something?


Solution

  • I'd just break the commands down into what it's doing instead of trying to mix concerns:

    var myItem = new MyItem() {Name = "Bob"};
    
    if (myItem.MyId == null)
    {
        mongoCollection.InsertOne(myItem);
    }
    else
    {
        mongoCollection.ReplaceOne(x => x.MyId == myItem.MyId, myItem);
    }
    

    Replacing on an id of null will just insert null as the _id for the document.