簡體   English   中英

在C#.Net中將多個BSon ObjectID反序列化為MongoDB文檔的字符串

[英]De-Serialize multiple BSon ObjectID to String of a MongoDB document in C# .Net

我需要反序列_id從價值和Boss_id ObjectIdstring使用C#.NET在MongoDB的集合中的所有文件

我的收款Employee是(這里我僅粘貼了2個文檔,實際上我有超過1萬個文檔)

{
    "_id" : ObjectId("575845a713d284da0ac2ee81"),
    "Boss_id" : ObjectId("575841b313d284da0ac2ee7d"),
    "Emp_Name" : "Raj",
}

{
    "_id" : ObjectId("575845d213d284da0ac2ee82"),
    "Boss_id" : ObjectId("575841b313d284da0ac2ee7d"),
    "Emp_Name" : "Kumar"
}

我的C#來源-模型類EmployeeModel

public class EmployeeModel
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }

    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Boss_Id { get; set; }

    public string Emp_Name { get; set; }
}

我的C#MongoDB代碼:

private static IMongoClient _client;
private static IMongoDatabase _database;

_client = new MongoClient();
_database = _client.GetDatabase("RMS");
var collection = _database.GetCollection<EmployeeModel>("Employee");

BsonDocument temp = new BsonDocument("Emp_Name", "Raj");
var cItem = collection.Find(temp).ToList();

if ((cItem != null) && (cItem.Count > 0))
{
    _EmpList = cItem;
} 

它的拋出異常

類型為MongoDB.Bson.Serialization.Attributes.BsonIdAttribute的屬性只能應用於單個成員。

請幫助我如何獲取文件?

試試下面的代碼。 [BsonId]是文檔的ID,因此在Json中,它是“ _id”元素。 僅此而已

public class EmployeeModel
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }


    [BsonRepresentation(BsonType.ObjectId)]
    public string Boss_Id { get; set; }

    public string Emp_Name { get; set; }
}

暫無
暫無

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

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