4

I'm trying to set the Id property of my class as combination of another 2 properties:

   public class Student
   {
       public string Id {get;set;}
       public Guid StudentNumber {get;set;]
       public string SchoolId {get;set;}
   }

I want that StudentNumber and SchoolId to be the Id of the object when I save it.

How can it be done?

1 Answer 1

6

Have a look at the IdGenerator classes to custom create an id from the two properties.

http://docs.mongodb.org/ecosystem/tutorial/serialize-documents-with-the-csharp-driver/

You'll need to create a new IdGenerator class which implements the IIdGenerator interface (docs). There are two simple methods to implement.

Do note that a document's _id cannot be changed once saved. You'd need to resave it as a new document. So, if the SchoolId property changes, you may need to recreate the document.

Also, you might just consider creating a composite index for the two fields and leave the _id as an ObjectId.

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

2 Comments

As this is a nearly 2.5 year old question -- this updated doc may not be relevant anymore. mongodb.github.io/mongo-csharp-driver/2.0/reference/bson/…

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.