[英]How to Insert a document with array of sub-documents by C# class
I'm amateur with mongodb and C# driver. 我对mongodb和C#驱动程序很业余。 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. 请帮我。
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);
您需要更新列表,因为该列表目前为空
en.score=new List<sc>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.