Paste without creating Id?

I created a simple object with getters and setters:

public class MemberCanonical : IMemberCanonical { public ObjectId Id { get; set; } public String username { get; set; } public String email { get; set; } public String status { get; set; } public IEnumerable<string> roles { get; set; } } 

Now I want to insert a new item into the database with:

 try { memberObj.username = username; memberObj.email = email; memberObj.status = "active"; // memberObj.Id = new ObjectId().ToString(); this.membershipcollection.Insert(memberObj, SafeMode.True); return true; } catch(Exception ex) { return false; } 

I would expect the insert to create a unique _id (Id), but that will not happen. After pasting, when I look at the _id field, I get "0000000 ...."

What do I need to do so that Mongo can generate its own _id on insertion?

+8
c # mongodb mongodb-.net-driver
source share
3 answers

Just mark the Id property with the [BsonId] attribute, and the generated id value will be created!

 public class MemberCanonical : IMemberCanonical { [BsonId] public ObjectId Id { get; set; } 

 this.membershipcollection.Insert(memberObj, SafeMode.True); var idYouLookingFor = memberObj.Id; 

Or an alternative method suggested by @Kobi: "use the field name _id instead of Id" should also work.

+11
source share

I use a combination of the [BsonId] attribute and the constructor to create the Id value.

for example

 public class Something { [BsonId] public string Id { get; set; } public Something() { this.Id = ObjectId.GenerateNewId().ToString(); } } 

This is so that I always have a completed Id field for the object. When an object is retrieved from the database, the Id field is overwritten with the actual Id value from the database. Win Win.

+4
source share

Use [BsonId] depending on which unique property you want to use. You can even ignore the ObjectID type and create your own.

For example:

 [BsonId] public string studentid{get; set;} 
-one
source share

All Articles