hotips
hotips

Reputation: 2631

MongoDB serialization with objects and arraylist of objects with official C# driver

I have this example class :

public class Test
{
        private ObjectId _mongoID;
        private A _a = new A();
        private ArrayList _alData = new ArrayList(); // Arraylist of B objects
        #endregion

        public Test(A a, ArrayList alData)
        {
            _a = a;
            _alData = alData;
        }

        [BsonId]
        public ObjectId MongoID
        {
            get;

            set;
        }

        public A a
        {
            get
            {
                return _a;
            }
        }

        public Array dta
        {
            get 
            {
                return _alData.ToArray();
            }
        }
}

I hope to have this result :

{ "_id" : ObjectId("000000000000000000000000"), "_a":{A members}, "dta":[{B members}, {B members}]}

How can I do ?

Thanks

Upvotes: 0

Views: 948

Answers (1)

Craig Wilson
Craig Wilson

Reputation: 12624

This class is readonly and immutable. Is that your intent? If so, then the below is the best way to accomplish what you are asking for. Note, you need to use at least driver version 1.4.1 for this to work and you cannot read this class from the database. It is persist only due to the readonly nature of the properties.

public class Test
{
  private A _a;
  private ArrayList _alData;

  [BsonId]
  public ObjectId Id { get; set;}

  [BsonElement("_a")]
  public A A { get { return _a; } }

  [BsonElement]
  public Array dta { get { return _alData.ToArray(); } }
}

Upvotes: 1

Related Questions