user3439809
user3439809

Reputation: 1

How to Insert a document with array of sub-documents by C# class

I'm amateur with mongodb and C# driver. I try to Insert a document with array of sub-documents by class. my codes are these: This is my classes:

    public class Entity
    {

        public string name { get; set; }
        public string family { get; set; }
        public List<sc> score { get; set; }
    }

    public class sc
    {
        public int Math{ get; set; }

        public int literature{ get; set; }
    }

And this is my code for fill fields and insert document:

        var en = new Entity();
        var sc1 = new sc();
        var sc2 = new sc();
        sc1.Math= 14;
        sc1.literature= 15;
        sc2.Math= 16;
        sc2.literature= 19;
        en.score[0] = sc1;
        en.score[1] = sc2;
        en.name = "Esi";
        en.family = "Moja";
        collection.Insert(en);

But i get this error when i run it:

Object reference not set to an instance of an object.

How can i fix this problem? Please help me.

Upvotes: 0

Views: 826

Answers (2)

fuzzybear
fuzzybear

Reputation: 2405

you need to new up your list as it's null at the moment

 en.score=new List<sc>();

Upvotes: 0

R&#233;da Mattar
R&#233;da Mattar

Reputation: 4381

This is because you don't initialize your list. Try this instead :

var en = new Entity();
var sc1 = new sc();
var sc2 = new sc();
sc1.Math= 14;
sc1.literature= 15;
sc2.Math= 16;
sc2.literature= 19;
en.score = new List<sc>(); // The missing line
en.score.Add(sc1); // How you add elements 
en.score.Add(sc2); // in your list
en.name = "Esi";
en.family = "Moja";
collection.Insert(en);

You can also use an object initializer, for better readability :

var en = new Entity()
         {
             name = "Esi",
             family = "Moja",
             score = new List<sc>
             {
                 new sc()
                 {
                     Math = 14,
                     Literature = 15
                 },
                 new sc()
                 {
                     Math = 16,
                     Literature = 19
                 }
             }
         }

collection.Insert(en);

Upvotes: 1

Related Questions