繁体   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