Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 381
goldfinger Avatar asked Oct 19 '25 08:10

goldfinger


1 Answers

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.

like image 135
Craig Wilson Avatar answered Oct 22 '25 02:10

Craig Wilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!