简体   繁体   English

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

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

I need to de-serialize the Value of _id and Boss_id from ObjectId to string for all document in a mongodb collection using C# .Net 我需要反序列_id从价值和Boss_id ObjectIdstring使用C#.NET在MongoDB的集合中的所有文件

My Collection Employee is (Here I pasted only 2 Documents, in real I'm having more than 10K Documents) 我的收款Employee是(这里我仅粘贴了2个文档,实际上我有超过1万个文档)

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

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

My C# Source - Model Class EmployeeModel 我的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; }
}

My C# MongoDB Code: 我的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;
} 

Its throwing Exception 它的抛出异常

Attributes of type MongoDB.Bson.Serialization.Attributes.BsonIdAttribute can only be applied to a single member. 类型为MongoDB.Bson.Serialization.Attributes.BsonIdAttribute的属性只能应用于单个成员。

kindly assist me how to fetch the documents ? 请帮助我如何获取文件?

Try the code below. 试试下面的代码。 [BsonId] is the id of the document so in the Json it's the "_id" element. [BsonId]是文档的ID,因此在Json中,它是“ _id”元素。 That's all it identifiies 仅此而已

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