发生System.NullReferenceException HResult = 0x80004003
Message =对象引用未设置为对象的实例 Source = StackTrace:at mongotest.Program.Main(String [] args)in C:\ Users \用户kiit \源\回购\ C#-code \ mongotest \ mongotest \ Program.cs中:线 20
请帮我解决这个错误。为什么我得到空引用。除此之外,请告诉我如何在MongoDB中获取此架构的数据
{
"_id" : ObjectId("5a78a7365a98c0a0d9118c1a"),
"name" : "Amit",
"contacts" : [
"userid1",
"userid2"
],
"logs" : {
"status" : "online",
"Available" : "False"
}
}
代码: 如何设置日志和联系人的值,我想在数据库中插入这些值。 我将对此解决方案做些什么:我将在asp.net中的click事件的数据库中插入值,并从用户获取值。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MongoDB.Bson;
using MongoDB.Driver;
namespace mongotest
{
class Program
{
static void Main(string[] args)
{
/* Connection in MongoDb and insert data in database */
var client = new MongoClient("mongodb://localhost");
var database = client.GetDatabase("SIH");
var collection = database.GetCollection<testing>("testing");
testing newobject = new testing();
newobject.name = "Amit Mishra";
newobject.logs.Available = "true";
newobject.logs.status = "false";
collection.InsertOneAsync(newobject);
Console.Write("Done");
Console.Read();
}
}
}
public class testing
{
public string _id { get; set; }
public string name { get; set; }
public string[] contacts { get; set; }
public Logs logs { get; set; }
}
public class Logs
{
public string status { get; set; }
public string Available { get; set; }
}
答案 0 :(得分:1)
您正在访问未初始化的属性,这就是您获取NullPointerException的原因。
将代码改为:
[...]
newobject.logs = new Logs();
newobject.logs.Available = "true";
[...]
答案 1 :(得分:0)
如dnickless所示,您必须初始化日志,并且还必须初始化字符串数组。 在您的情况下,代码应该增强到类似:
[...]
newobject.logs = new Logs();
newobject.logs.Available = "true";
newobject.contacts = new string[]{ "userid1", "userid2" };
[...]