2
I’m having the following mistake:
Object Reference not set to an instance of an Object
Can anyone identify which error in my code?
Follow my classes:
Program
:
class Program {
static void Main(string[] args) {
using(var db = new StudentContext()) {
var student = new Student() {
Name = "Kelly Soares"
};
var mathSubj = new Subject() {
Name = "Mathematics"
};
var scienceSubj = new Subject() {
Name = "Data Structures"
};
student.Subjects.Add(mathSubj);
student.Subjects.Add(scienceSubj);
db.Students.Add(student);
db.SaveChanges();
}
}
}
Student
:
public class Student {
public int StudentId {
get;
set;
}
public string Name {
get;
set;
}
public virtual List Subjects {
get;
set;
}
}
Subject
:
public class Subject {
public int SubjectId {
get;
set;
}
public string Name {
get;
set;
}
public virtual Student Students {
get;
set;
}
}
StudentContext
:
public class StudentContext: DbContext {
public StudentContext(): base(@"Data Source=(local); Initial Catalog=tempdb; Integrated Security=true") {
}
public DbSet < Student > Students {
get;
set;
}
public DbSet < Subject > Subjects {
get;
set;
}
}
On which line the error occurs?
– Leonel Sanches da Silva
It is very likely that you are not using version 6 of
ef
and theLists
are not being initialized alone...– Jéf Bueno
Bruno, he’s already making an error on this student.Thesubjects Add(mathSubj) line; so he tries to make the first insertion.
– Kelly Soares
You can also put the Stack Trace in your question, please?
– Leonel Sanches da Silva