将 C# 对象映射到 BsonDocument
Mapping C# object to BsonDocument
我对 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; }
}
我的问题是在映射时,我应该使用什么属性,以便 User 对象与 Question 对象反序列化。 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" }]
}
我对 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
是另一个定义为 :
[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; }
}
我的问题是在映射时,我应该使用什么属性,以便 User 对象与 Question 对象反序列化。 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" }]
}