【发布时间】:2016-02-14 01:50:45
【问题描述】:
我正在使用Mongo .Net Driver 查询 MongoDB 数据库,我想将返回的 Bson 文档映射到我的 Customer Object Poco。
为了做到这一点,我创建了一个LoadCustomers() 以从查询的 Bson 文档中返回一个反序列化的客户列表。
在我的 Customer POCO 类中,每个属性都标有 BsonElement 标签,这应该有助于将 Bson 映射到 Object。
但是当我尝试使用来自 this answer 的 FindAs 进行反序列化时,我收到一个编译器错误,指出没有这样的方法。
如何使用 MongoDB .Net 驱动程序将 MongoDB Bson 文档作为 POCO 列表返回?
这是我目前对加载方法的尝试:
public static List<Customer> LoadCustomers()
{
var client = new MongoClient(connectionString);
var database = client.GetDatabase("orders");
//Get a handle on the customers collection:
var docs = database.FindAs<Customer>("customers");
return docs;
}
下面是我的客户 POCO,显示了文档中的字段:
public class Customer
{
/// <summary>
/// This attribute is used to map the Id property to the ObjectId in the collection
/// </summary>
[BsonId]
public ObjectId Id { get; set; }
[BsonElement("firstName")]
public string firstName { get; set; }
[BsonElement("lastName")]
public string lastName { get; set; }
[BsonElement("email")]
public string Email { get; set; }
}
【问题讨论】:
标签: c# mongodb-.net-driver poco bson json-deserialization