![](/img/trans.png)
[英]How do I return a document with filtered sub-documents using Mongo.Driver.Linq with the Mongo C# driver 2.3?
[英]How to Insert a document with array of sub-documents by C# class
我對mongodb和C#驅動程序很業余。 我嘗試按類插入包含子文檔數組的文檔。 我的代碼是:這是我的課程:
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; }
}
這是我用於填充字段和插入文檔的代碼:
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);
但是我在運行它時收到此錯誤:
Object reference not set to an instance of an object.
我該如何解決這個問題? 請幫我。
這是因為您沒有初始化列表。 試試這個代替:
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);
您還可以使用對象初始化程序,以提高可讀性:
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.