简体   繁体   English

使用 mongoDB 自动生成的 id

[英]Auto Generated id using mongoDB

I am developing a desktop application using windows forms c#, I've created an unique index named Id in my database.我正在使用 windows forms c# 开发桌面应用程序,我在我的数据库中创建了一个名为 Id 的唯一索引。

But now I want it when I send a class with field 'Id' empty so the database gives it a unique value by its own.但是现在当我发送一个字段“Id”为空的 class 时,我想要它,因此数据库自己给它一个唯一的值。

I am sorry for not illustrating well and also the problem may seem easy, but I don't know how because i am still a beginner很抱歉没有很好地说明问题,而且问题似乎很简单,但我不知道怎么做,因为我还是个初学者

Thanks in advance.提前致谢。

No need to create a unique index yourself.无需自己创建唯一索引。 MongoDB creates a unique index on the _id field during the creation of a collection. MongoDB 在创建集合期间在_id字段上创建唯一索引。

If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.如果插入的文档省略了 _id 字段,MongoDB 驱动程序会自动为 _id 字段生成ObjectId ObjectId essentially a timestamp plus random value. ObjectId 本质上是一个时间戳加上随机值。

In your models, you can map to _id field using attributes在您的模型中,您可以使用属性 map 到 _id 字段

[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM