0

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.

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.