簡體   English   中英

將 C# object 映射到 BsonDocument

[英]Mapping C# object to BsonDocument

我對 MongoDB 比較陌生。 我有一個具有以下定義的 object

[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; }
}

我的問題是在映射時,我應該使用什么屬性以便用戶 object 使用 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.Driver; 使用 MongoDB.Bson;

暫無
暫無

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

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