gpt4 book ai didi

c# - 在 MongoDB 中查找和反序列化对象

转载 作者:可可西里 更新时间:2023-11-01 09:13:11 61 4
gpt4 key购买 nike

我尝试使用 MongoDB 驱动程序反序列化对象,但出现错误。我的代码和mongodb官网的例子代码很像,找不到哪里错了。

这是错误:

"Element '_id' does not match any field or property of class mongotry.place."

还有代码:

using MongoDB.Driver;
using MongoDB.Bson;

class place{
public string name { get; set; }
public List<int> rates { get; set; }

public place(string name, List<int> rates){...}
public int getAvgRate(){...}
public override string ToString(){...}
}

class Program{
static void Main(string[] args){
MongoClient client = new MongoClient();
MongoServer server = client.GetServer();
MongoDatabase db = server.GetDatabase("try");
MongoCollection<place> myPlaces = db.GetCollection<place>("places");

myPlaces.Insert(new place("here", new List<int> {7,7,5,4,9}););
myPlaces.Insert(new place("there", new List<int> { 2, 4, 1, 4});); //ok so far

place placeFromDB = myPlaces.FindOne(); // <-- here is the error.
Console.WriteLine(placeFromDB.ToString());
Console.ReadLine();
}
}

最佳答案

只需将 id 属性添加到您的地点类:

public ObjectId Id { get; set; }

您还可以使用 [BsonId] 属性标记您的名称属性,但是拥有 ObjectId 属性更强大 - 它本身包含时间戳/增量 ID/机器信息并且始终是唯一的。

关于c# - 在 MongoDB 中查找和反序列化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20151071/

61 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com