简体   繁体   English

如何将MongoDb _id绑定到属性?

[英]How to bind a MongoDb _id to a property?

I want to connect my ASP.NET Core web app to MongoDB, but got an issue. 我想将我的ASP.NET Core Web应用程序连接到MongoDB,但是遇到了问题。

I have a little model of Car 我有一个小车模

[BsonRepresentation(BsonType.ObjectId)]
public ObjectId ID { get; set; }
public string Company { get; set; }
public string Model { get; set; }
public string Color { get; set; }

[Range(1, 100)]
[DataType(DataType.Currency)]
public double Price { get; set; }

I also have a method which adds first data to my database: (in future I will add a method to the controller) 我也有一个方法可以向数据库中添加第一个数据:(以后我将向控制器中添加一个方法)

public async Task AddCar()
        {
            var mycar = new Car
            {
                Color = "red",
                Company = "my",
                Model = "x3",
                Price = 33
            };
            var collection = database.GetCollection<Car>("car");
            await collection.InsertOneAsync(mycar);
        }

Everything looks good, but when I run my program I get this data in DB 一切看起来都不错,但是当我运行程序时,我在DB中获得了这些数据 我的数据库中的文档

I want that the automatically generated _id property is matched with my ID property 我希望自动生成的_id属性与我的ID属性匹配

What do I have to do to accomplish this? 我必须怎么做才能做到这一点?

You need to add the [BsonId] decorator before the [BsonRepresentation] one to tell MongoDB you are referring to it's autogenerated document ID. 您需要添加[BsonId]的前装饰[BsonRepresentation]人告诉MongoDB的你指的是它的自动生成的文件ID。 What happens now is MongoDB adding ID to the document while creating it and also another ID (yours) that's represented as the ObjectId but since you aren't really generating the value for your ObjectId , it's a bunch of zeroes. 现在发生的是MongoDB在创建文档时将ID添加到文档中,还添加了另一个ID(您自己),该ID表示为ObjectId但是由于您并没有真正为ObjectId生成值,因此它是一堆零。

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

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