Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping C# object to BsonDocument

I am relatively new to MongoDB. I have an object with the following definition

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

Where Questions is another BsonDocument defined as :

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

My Question is while mapping, what attribute should I use so that the User object deserializes with the Question objects. There is no [BsonDocument] attibute in C# Driver.

like image 784
progrAmmar Avatar asked Mar 18 '16 05:03

progrAmmar


1 Answers

I'm not sure where are you stuck but try:

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

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

Console.WriteLine (jsonDocument);

It will print:

{ 
   "_id" : null, 
   "username" : "invisible", 
   "email" : "[email protected]", 
   "Questions" : [{ "_id" : null, "title" : "Q", "desc" : "Question to ask" }] 
}
like image 174
Saleem Avatar answered Sep 28 '22 04:09

Saleem