在C# .Net中将多个BSon ObjectID反序列化为MongoDB文档的字符串



我需要使用 C# .Net 将 mongodb 集合中所有文档的 _id 和Boss_id值从 ObjectId 反序列化为 string

我的收藏Employee是(这里我只粘贴了 2 个文档,实际上我有超过 10K 个文档)

{
    "_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; }
}