简体   繁体   中英

How to deserialize a Bson document to a POCO?

I'm using the Mongo .Net Driver to query a MongoDB database and I want to map the returned Bson document to my Customer Object Poco.

In order to do this I created a LoadCustomers() to return a de-serialized list of customers from the queried Bson document.

In my Customer POCO class, each property is marked with BsonElement tag which should assist the mapping of Bson to Object.

But when I tried to deserialize using the FindAs<> from this answer , I get a compiler error stating that there is no such method.

How can I return the MongoDB Bson document as a POCO list, using MongoDB .Net driver?

This is my current attempt at the load method:

    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;            
    } 

Below is my Customer POCO, showing the fields within the document:

    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; }

    }

If you want to select all Customers in a Collection use something like this:

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

For querying a single document by id, something like this should be used:

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

Assuming you are using the latest driver, First you have to get the collection and then do your query on the collection. Something like this

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;            
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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