1

It says here (http://mongodb.github.io/mongo-csharp-driver/2.2/reference/bson/mapping/#id-generators) that the driver should use one of the builtin ID generators to generate a new ID for properties ID, id, _id (convention).

I have a model with

public string Id { get;set; }

and the automatic ID generation is not happening. Inserted document has an ID of null.

Snippet from my repository code:

    public void Save<TEntity>(TEntity item) where TEntity : class, new()
    {
        var collection = GetCollection<TEntity>();
        collection.InsertOne(item);
    }
3
  • please include a verifiable sample code to ensure we all are on same page. For clarification, what is your MongoDB and driver version? Your post title says its 2.0 while reference link is pointing to 2.2 Commented May 22, 2016 at 5:21
  • MongoDB 3.2.6 and Mongo driver 2.2.3 Commented May 22, 2016 at 14:13
  • My code is simple, pretty much simple models with straightforward CRUD code, see above Commented May 22, 2016 at 14:14

1 Answer 1

1

After further troubleshooting I got this working.

Had to put attribute [BsonId] set to StringObjectIdGenerator to Id properties.

[BsonId(IdGenerator = typeof(StringObjectIdGenerator))]

The docs at http://mongodb.github.io/mongo-csharp-driver/2.2/reference/bson/mapping/#id-generators are certainly misleading or not clear enough

Some of these Id generators are used automatically for commonly used Id types: GuidGenerator is used for a Guid ObjectIdGenerator is used for an ObjectId StringObjectIdGenerator is used for a string represented externally as ObjectId

I've opened an issue with MongoDb JIRA tracker and I'll post their reply here if they provide any insight into that.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.