I'm having the following error:
Object reference not set to an instance of an object
Can anyone identify the 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;
}
}