在mongodb c#驱动程序中使用POCO时如何管理_id字段 [英] how to manage _id field when using POCO with mongodb c# driver

查看:90
本文介绍了在mongodb c#驱动程序中使用POCO时如何管理_id字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想使用POCO读写mongo数据

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

当我回读时,我失败了,说_id是一个意外的属性(它是).因此,我在类中添加了一个名为_id的字段.现在,插入内容不起作用,说明_id字段不能为null.尝试过的BsonIgnoreIfNull属性无法正常工作.

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.

推荐答案

插入对象时,如果它没有_id字段,则驱动程序将其添加并将其设置为12字节的MongoDB ObjectId 值.

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.

您只需要在POCO中添加一个Id属性,该属性将从_id反序列化:

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; }
}

或者,如果您想委托另一个属性映射到_id,则可以使用BsonIdAttribute装饰它,如下所示:

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; }   

_id字段不必是MongoDB ObjectId,您可以将其设置为任何数据类型的任何值(数组除外),只需在集合中唯一即可.

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.

这篇关于在mongodb c#驱动程序中使用POCO时如何管理_id字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆