gpt4 book ai didi

c# - 将 C# 对象映射到 BsonDocument

转载 作者:IT老高 更新时间:2023-10-28 13:20:06 27 4
gpt4 key购买 nike

我对 MongoDB 比较陌生。我有一个具有以下定义的对象

[BsonDiscriminator("user")]
public Class BrdUser
{
[BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
public string ID { get; set; }

[BsonElement("username")]
public string UserNm { get; set; }

[BsonElement("email")]
public string EmailAdrs { get; set; }
.
.
.
public IList<Question> Questions{ get; set; } //<-- Un sure as to what Bson type should this be
}

Questions 是另一个 BsonDocument,定义为:

[BsonDiscriminator("userques")]
public class Question
{
[BsonId(IdGenerator = typeof(StringObjectIdGenerator))]
public string ID { get; set; }

[BsonElement("title")]
public string Title{ get; set; }

[BsonElement("desc")]
public string Desciption{ get; set; }
}

我的问题是在映射时,我应该使用什么属性以便用户对象与问题对象反序列化。 C#驱动中没有[BsonDocument]属性。

最佳答案

我不确定你在哪里卡住了,但试试:

var brdDoc = new BrdUser ();
brdDoc.UserNm = "invisible";
brdDoc.EmailAdrs = "someone@womewhere.com";
brdDoc.Questions = new []{ new Question{ Title = "Q", Desciption = "Question to ask" } };

var bsonDocument = brdDoc.ToBsonDocument ();
var jsonDocument = bsonDocument.ToJson ();

Console.WriteLine (jsonDocument);

它将打印:

{ 
"_id" : null,
"username" : "invisible",
"email" : "someone@womewhere.com",
"Questions" : [{ "_id" : null, "title" : "Q", "desc" : "Question to ask" }]
}

关于c# - 将 C# 对象映射到 BsonDocument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36076623/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com