Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
833 views
in Technique[技术] by (71.8m points)

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

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"));

When I read back I get a failure saying that _id is an unexpected attribute (which it is). So then I added a field called _id to the class. Now the insert doesnt work saying that the _id field cannot be null. A tried BsonIgnoreIfNull attribute, that didnt work.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...