【问题标题】:How to deserialize a Bson document to a POCO?如何将 Bson 文档反序列化为 POCO?
【发布时间】: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


    【解决方案1】:

    如果您想选择集合中的所有客户,请使用以下内容:

    var docs = await database.GetCollection<Customer>("customers").Find(new BsonDocument()).ToListAsync();
    

    对于通过 id 查询单个文档,应该使用类似这样的方法:

    var filter = Builders<Customer>.Filter.Eq(c => c.Id, <ID>);
    var result = await database.GetCollection<Customer>("customers").Find(filter).FirstOrDefaultAsync();
    

    【讨论】:

    • 如果出现不匹配类的任何字段或属性(即 _class 或 _id)错误,请记住使用 [BsonIgnoreExtraElements] 注释 POCO
    【解决方案2】:

    假设您使用的是最新的驱动程序,首先您必须获取集合,然后对集合进行查询。像这样的

    public static List<Customer> LoadCustomers()
    {
        var client = new MongoClient(connectionString);
        var database = client.GetDatabase("orders");
        //Get a handle on the customers collection:
        var collection = database.GetCollection<Customer>("customers");
        var docs = collection.Find(new BsonDocument()).ToListAsync().GetAwaiter().GetResult();
        return docs;            
    } 
    

    【讨论】:

    • 我现在需要从我拥有的新集合中返回一个列表,但不确定如何仅从模型中返回列表。如果您有任何建议,我在上面发布了一个问题:stackoverflow.com/questions/34077614/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-02
    • 1970-01-01
    • 2015-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多