如何通过C#类将包含子文档数组的文档插入到MongoDB中? [英] How to Insert a document with array of subDocuments into MongoDB by C# classes?

查看:110
本文介绍了如何通过C#类将包含子文档数组的文档插入到MongoDB中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


我是mongodb和C#驱动程序的业余爱好者。

我尝试按类别插入包含子文档数组的文档。

my代码是这些:

这是我的课程:

  public   class 实体
{

public string name { get ; set ; }
public string family { get ; set ; }
public 列表< sc>得分{得到; set ; }
}

public class sc
{
public int 数学{获取; set ; }

public int copyright {获得; set ; }
}





这是我填写字段的代码并插入文档:

< pre lang =c#> 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);





但是当我运行它时会出现这个错误:

 对象引用不是 set  object 





我该如何解决这个问题?请帮帮我。

解决方案

Hi 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.

解决方案

这篇关于如何通过C#类将包含子文档数组的文档插入到MongoDB中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆