how to manage _id field when using POCO with mongodb c# driver

后端 未结 5 2050
面向向阳花
面向向阳花 2020-12-14 01:01

If I want to read and write mongo data with a POCO

public class Thingy
{
     public string Foo {get;set;}
}
...
coll.Insert(new Thing(Foo = \"hello\"));


        
相关标签:
5条回答
  • 2020-12-14 01:52

    Add a property as follows:

    public BsonObjectId Id { get; set; }
    

    The MongoDB driver automatically converts Id to _id during serialization\deserializtion.

    0 讨论(0)
  • 2020-12-14 01:52
    public class Thingy
    {
          public ObjectId Id { get; set; }
          public string Foo { get; set; }
    }
    

    According to class

    Where needed, use the following code:

    var collection = database.GetCollection<Thingy>("db_Thingy");
    Thingy tg= new Thingy();
    tg.Foo = "Hello";
    collection.insert(tg);
    
    0 讨论(0)
  • 2020-12-14 01:53

    I generally wrap Thingy:

    public class MongoThingy
    {
        public ObjectId Id { get; set; }
        public Thingy Thingy { get; set; }
    }
    

    It makes it a lot easier, as often times class Thingy comes from a different library over which I have no control. It's also easier to deserialize in order to hand it over to someone else for processsing.

    0 讨论(0)
  • 2020-12-14 01:55

    When you insert an object, if it doesn't have an _id field then the driver adds one and sets it to a 12-byte MongoDB ObjectId value.

    You just need to add an Id property to your POCO, which will be deserialised from _id:

    public class Thingy
    {
         public ObjectId Id { get; set; }
    }
    

    Or, if you'd like to delegate another property to map onto _id then you can decorate it with the BsonIdAttribute, like this:

    [BsonId]
    public ObjectId MyKey { get; set; }   
    

    The _id field doesn't have to be an MongoDB ObjectId, you can set it to any value of any data type (except an array), it just needs to be unique within the collection.

    0 讨论(0)
  • 2020-12-14 02:04

    You have to add a property (or field) for id and tell serializer which id generator you'd like to use.

    [BsonId(IdGenerator = typeof(ObjectIdGenerator))]
    public object ThingyId { get; set; }
    

    There are 3 available in MongoDb Driver or you can write your own. More info at http://www.mongodb.org/display/DOCS/CSharp+Driver+Serialization+Tutorial#CSharpDriverSerializationTutorial-WriteacustomIdgenerator

    0 讨论(0)
提交回复
热议问题