Search code examples
mongodbmongodb-.net-driver

C# MongoDB - binding object properties, _id null on insert


When I insert to Mongo, I do not want to define _id, but I do want to READ _id. When using an object such as

public class MyClass
    {
        public Object _id { get; set;}
        public String propery1 { get; set; }
    }

I am writing null _id if I do something like

this.myobj.property1 = "Useless info";    
SafeModeResult result = this.uploads.Insert(uploadedfilecanonical, SafeMode.True);

Do I need to create separate class types for query binding vs. insert binding, where insert does not define _id property but queryable does?


Solution

  • I'm not really understanding your question, so I'll do my best here. If you do an insert, if the _id is null, it will persist null. If you use Save, it will create an identifier for you if one doesn't exist. However, you are using an Object as your id, which is rather odd. We suggest you use an ObjectId, an integer, a Guid, or something.

    In addition, you can use a property called "Id" instead of the non-conventional _id for a .NET class. Alternatively, you can use an attribute to denote the id or you can create a convention to apply a common pattern. I highly suggest reading the tutorial for more information.