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:
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:
Am I missing something?
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.