Search code examples
c#mongodbmongodb-.net-driver

C# MongoDB AutoGenerateId without attributes


I have the following class:

public class Foo : IFoo
{
    public object Id { get; set; }
    public string someProperty { get; set;}
}

If you notice, the Id property it's an object type. This is very important because I don't wanna to have any MongoDb dependence on my Models, thus the same models will be used in others databases repositories.

So I have my FooMongoDBRepository where my class map are defined:

    public class FooMongoDBRepository : IFooRepository{

        public MongoDbSubscriberRepository (MongoDatabase database){
            BsonSerializer.LookupSerializer(typeof(Foo));
            if (!BsonClassMap.IsClassMapRegistered (typeof(Foo))) {
                BsonClassMap.RegisterClassMap<Foo> (cm => {
                    cm.AutoMap ();
                    cm.SetIdMember (cm.GetMemberMap (c => c.Id));
                });
            }

        }
     }

This work fine for inserts, but when try to Upsert, my _id key is always NULL. Can someone help me, how to force the Id field to be generated without using annotations ?

Thanks in advanced!

Edit: Now It's working!, here is the code

                cm.AutoMap ();
                cm.GetMemberMap(c => c.Id).SetIgnoreIfDefault(true);
                cm.SetIdMember (cm.GetMemberMap (c => c.Id));
                cm.IdMemberMap.SetIdGenerator(ObjectIdGenerator.Instance);

Solution

  • You need to add

    [BsonIgnoreIfDefault] to your Id

    BsonClassMap.RegisterClassMap<MyClass>(cm => {
        cm.AutoMap();
        cm.GetMemberMap(c => c.SomeProperty)
            .SetDefaultValue("abc")
            .SetIgnoreIfDefault(true);
    });
    

    The sample above can be found here