簡體   English   中英

如何將Bson文檔反序列化為POCO?

[英]How to deserialize a Bson document to a POCO?

我正在使用Mongo .Net Driver查詢MongoDB數據庫,我想將返回的Bson文檔映射到我的Customer Object Poco。

為了做到這一點,我創建了一個LoadCustomers()來從查詢的Bson文檔中返回一個反序列化的客戶列表。

在我的Customer POCO類中,每個屬性都標有BsonElement標記,該標記應該有助於將Bson映射到Object。

但是當我嘗試使用此答案中的FindAs <>反序列化時,我收到編譯器錯誤,指出沒有這樣的方法。

如何使用MongoDB .Net驅動程序將MongoDB Bson文檔作為POCO列表返回?

這是我目前對load方法的嘗試:

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

    }

如果要選擇集合中的所有客戶,請使用以下內容:

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();

假設您使用的是最新的驅動程序,首先您必須獲取該集合,然后對該集合進行查詢。 像這樣的東西

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM